Skip to main content

Packet

Struct Packet 

Source
pub struct Packet {
    pub length: u32,
    pub payload: Vec<u8>,
}
Expand description

A USB HID message: the inner body plus its length, framed and chunked into HID reports on the wire. The USB counterpart to crate::Packet (no magic header).

Fields§

§length: u32§payload: Vec<u8>

Implementations§

Source§

impl Packet

Source

pub fn new(payload: Vec<u8>) -> Self

Examples found in repository?
examples/cli.rs (line 233)
232fn write_usb(file: &File, body: Vec<u8>) -> Result<(), DynErr> {
233    let bytes = usb::Packet::new(body).to_bytes();
234    let mut f: &File = file;
235    for chunk in bytes.chunks(usb::REPORT_SIZE) {
236        f.write_all(chunk)?;
237    }
238    Ok(())
239}
More examples
Hide additional examples
examples/usb_monitor.rs (line 18)
11fn main() -> Result<(), Box<dyn std::error::Error>> {
12    let path = env::args_os()
13        .nth(1)
14        .ok_or("usage: usb_monitor <path-to-hidraw>")?;
15    let file = OpenOptions::new().read(true).write(true).open(path)?;
16
17    // The device stays silent until a client requests its initial full sync.
18    (&file).write_all(&usb::Packet::new(usb::HANDSHAKE_BODY.to_vec()).to_bytes())?;
19
20    let mut session = ProtocolSession::new();
21    let mut buffered = Vec::new();
22    let mut report = [0_u8; usb::REPORT_SIZE];
23    loop {
24        let read = (&file).read(&mut report)?;
25        buffered.extend_from_slice(&report[..read]);
26
27        loop {
28            let len = match usb::scan_frame(&buffered) {
29                FrameScan::Complete { len } => len,
30                FrameScan::Incomplete => break,
31                FrameScan::Desync => {
32                    buffered.drain(..usb::REPORT_SIZE.min(buffered.len()));
33                    continue;
34                }
35            };
36            let (packet, consumed) = usb::Packet::from_bytes(&buffered[..len])
37                .ok_or("USB scanner returned an invalid packet")?;
38            buffered.drain(..consumed);
39
40            match session.ingest(&packet.payload)? {
41                SessionUpdate::Ready { initial_events } => {
42                    let capabilities = session.capabilities().unwrap();
43                    println!(
44                        "connected: {} fw {} ({} faders, {} sources, {} mixes)",
45                        capabilities.model(),
46                        capabilities.firmware().unwrap_or("unknown"),
47                        capabilities.faders().len(),
48                        capabilities.sources().len(),
49                        capabilities.mix_outputs().len(),
50                    );
51                    println!("initial state: {} typed events", initial_events.len());
52                }
53                SessionUpdate::Event(event) => println!("{event:?}"),
54                SessionUpdate::NeedsFullSync => {
55                    eprintln!("layout changed, requesting a fresh full sync");
56                    (&file)
57                        .write_all(&usb::Packet::new(usb::HANDSHAKE_BODY.to_vec()).to_bytes())?;
58                }
59            }
60        }
61    }
62}
Source

pub fn to_bytes(&self) -> Vec<u8> ⓘ

Serialize to the full HID wire form: [u32 LE len][body] chunked into REPORT_PAYLOAD-byte pieces, each prefixed with REPORT_ID_OUT and the last zero-padded to REPORT_SIZE. Write it to the device in REPORT_SIZE-byte chunks, one report per HID write.

Examples found in repository?
examples/cli.rs (line 233)
232fn write_usb(file: &File, body: Vec<u8>) -> Result<(), DynErr> {
233    let bytes = usb::Packet::new(body).to_bytes();
234    let mut f: &File = file;
235    for chunk in bytes.chunks(usb::REPORT_SIZE) {
236        f.write_all(chunk)?;
237    }
238    Ok(())
239}
More examples
Hide additional examples
examples/usb_monitor.rs (line 18)
11fn main() -> Result<(), Box<dyn std::error::Error>> {
12    let path = env::args_os()
13        .nth(1)
14        .ok_or("usage: usb_monitor <path-to-hidraw>")?;
15    let file = OpenOptions::new().read(true).write(true).open(path)?;
16
17    // The device stays silent until a client requests its initial full sync.
18    (&file).write_all(&usb::Packet::new(usb::HANDSHAKE_BODY.to_vec()).to_bytes())?;
19
20    let mut session = ProtocolSession::new();
21    let mut buffered = Vec::new();
22    let mut report = [0_u8; usb::REPORT_SIZE];
23    loop {
24        let read = (&file).read(&mut report)?;
25        buffered.extend_from_slice(&report[..read]);
26
27        loop {
28            let len = match usb::scan_frame(&buffered) {
29                FrameScan::Complete { len } => len,
30                FrameScan::Incomplete => break,
31                FrameScan::Desync => {
32                    buffered.drain(..usb::REPORT_SIZE.min(buffered.len()));
33                    continue;
34                }
35            };
36            let (packet, consumed) = usb::Packet::from_bytes(&buffered[..len])
37                .ok_or("USB scanner returned an invalid packet")?;
38            buffered.drain(..consumed);
39
40            match session.ingest(&packet.payload)? {
41                SessionUpdate::Ready { initial_events } => {
42                    let capabilities = session.capabilities().unwrap();
43                    println!(
44                        "connected: {} fw {} ({} faders, {} sources, {} mixes)",
45                        capabilities.model(),
46                        capabilities.firmware().unwrap_or("unknown"),
47                        capabilities.faders().len(),
48                        capabilities.sources().len(),
49                        capabilities.mix_outputs().len(),
50                    );
51                    println!("initial state: {} typed events", initial_events.len());
52                }
53                SessionUpdate::Event(event) => println!("{event:?}"),
54                SessionUpdate::NeedsFullSync => {
55                    eprintln!("layout changed, requesting a fresh full sync");
56                    (&file)
57                        .write_all(&usb::Packet::new(usb::HANDSHAKE_BODY.to_vec()).to_bytes())?;
58                }
59            }
60        }
61    }
62}
Source

pub fn from_bytes(buf: &[u8]) -> Option<(Self, usize)>

Parse one message from a buffer of raw HID reports (each REPORT_SIZE bytes as read from the device), returning it and the raw byte count to drain (a whole number of reports). None unless buf begins with a complete, valid message. The report-id byte of each report is ignored, so this decodes both REPORT_ID_OUT and REPORT_ID_IN streams.

Examples found in repository?
examples/cli.rs (line 276)
250fn usb_reader_loop(
251    file: Arc<File>,
252    layout: Shared<Option<Layout>>,
253    root: Shared<Option<Node>>,
254    watch: Arc<AtomicBool>,
255) {
256    let mut buf = Vec::<u8>::with_capacity(usb::REPORT_SIZE * 4);
257    let mut report = [0u8; usb::REPORT_SIZE];
258    loop {
259        let mut f: &File = &file;
260        let n = match f.read(&mut report) {
261            Ok(0) => return, // EOF: device went away or main dropped its handle
262            Ok(n) => n,
263            Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
264            Err(_) => return,
265        };
266        buf.extend_from_slice(&report[..n]);
267        loop {
268            match usb::scan_frame(&buf) {
269                FrameScan::Incomplete => break,
270                FrameScan::Desync => {
271                    // One report's worth is junk; drop and rescan.
272                    let drop = usb::REPORT_SIZE.min(buf.len());
273                    buf.drain(..drop);
274                }
275                FrameScan::Complete { len } => {
276                    let Some((packet, consumed)) = usb::Packet::from_bytes(&buf[..len]) else {
277                        buf.drain(..len);
278                        continue;
279                    };
280                    buf.drain(..consumed);
281                    handle_body(packet.payload, &layout, &root, &watch);
282                }
283            }
284        }
285    }
286}
More examples
Hide additional examples
examples/usb_monitor.rs (line 36)
11fn main() -> Result<(), Box<dyn std::error::Error>> {
12    let path = env::args_os()
13        .nth(1)
14        .ok_or("usage: usb_monitor <path-to-hidraw>")?;
15    let file = OpenOptions::new().read(true).write(true).open(path)?;
16
17    // The device stays silent until a client requests its initial full sync.
18    (&file).write_all(&usb::Packet::new(usb::HANDSHAKE_BODY.to_vec()).to_bytes())?;
19
20    let mut session = ProtocolSession::new();
21    let mut buffered = Vec::new();
22    let mut report = [0_u8; usb::REPORT_SIZE];
23    loop {
24        let read = (&file).read(&mut report)?;
25        buffered.extend_from_slice(&report[..read]);
26
27        loop {
28            let len = match usb::scan_frame(&buffered) {
29                FrameScan::Complete { len } => len,
30                FrameScan::Incomplete => break,
31                FrameScan::Desync => {
32                    buffered.drain(..usb::REPORT_SIZE.min(buffered.len()));
33                    continue;
34                }
35            };
36            let (packet, consumed) = usb::Packet::from_bytes(&buffered[..len])
37                .ok_or("USB scanner returned an invalid packet")?;
38            buffered.drain(..consumed);
39
40            match session.ingest(&packet.payload)? {
41                SessionUpdate::Ready { initial_events } => {
42                    let capabilities = session.capabilities().unwrap();
43                    println!(
44                        "connected: {} fw {} ({} faders, {} sources, {} mixes)",
45                        capabilities.model(),
46                        capabilities.firmware().unwrap_or("unknown"),
47                        capabilities.faders().len(),
48                        capabilities.sources().len(),
49                        capabilities.mix_outputs().len(),
50                    );
51                    println!("initial state: {} typed events", initial_events.len());
52                }
53                SessionUpdate::Event(event) => println!("{event:?}"),
54                SessionUpdate::NeedsFullSync => {
55                    eprintln!("layout changed, requesting a fresh full sync");
56                    (&file)
57                        .write_all(&usb::Packet::new(usb::HANDSHAKE_BODY.to_vec()).to_bytes())?;
58                }
59            }
60        }
61    }
62}

Trait Implementations§

Source§

impl Clone for Packet

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Packet

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Packet

Source§

impl PartialEq for Packet

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Packet

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.