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
impl Packet
Sourcepub fn new(payload: Vec<u8>) -> Self
pub fn new(payload: Vec<u8>) -> Self
Examples found in repository?
More 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}Sourcepub fn to_bytes(&self) -> Vec<u8> ⓘ
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?
More 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}Sourcepub fn from_bytes(buf: &[u8]) -> Option<(Self, usize)>
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
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§
impl Eq for Packet
impl StructuralPartialEq for Packet
Auto Trait Implementations§
impl Freeze for Packet
impl RefUnwindSafe for Packet
impl Send for Packet
impl Sync for Packet
impl Unpin for Packet
impl UnsafeUnpin for Packet
impl UnwindSafe for Packet
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more