Skip to content

Commit

Permalink
Merge pull request #41 from rust-embedded-community/rs/bugfix
Browse files Browse the repository at this point in the history
Fixing embedded-io issue, must poll endpoint before checking read buffer
  • Loading branch information
eldruin authored Nov 17, 2023
2 parents 26a2495 + 4b5c090 commit fb83286
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 13 deletions.
1 change: 1 addition & 0 deletions src/io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ impl<Bus: UsbBus> embedded_io::Read for SerialPort<'_, Bus> {

impl<Bus: UsbBus> embedded_io::ReadReady for SerialPort<'_, Bus> {
fn read_ready(&mut self) -> Result<bool, Self::Error> {
self.poll()?;
Ok(self.read_buf.available_read() != 0)
}
}
Expand Down
33 changes: 20 additions & 13 deletions src/serial_port.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,23 @@ where
}
}

/// Poll the endpoint and try to put them into the serial buffer.
pub(crate) fn poll(&mut self) -> Result<()> {
let Self {
inner, read_buf, ..
} = self;

read_buf.write_all(inner.max_packet_size() as usize, |buf_data| {
match inner.read_packet(buf_data) {
Ok(c) => Ok(c),
Err(UsbError::WouldBlock) => Ok(0),
Err(err) => Err(err),
}
})?;

Ok(())
}

/// Reads bytes from the port into `data` and returns the number of bytes read.
///
/// # Errors
Expand All @@ -146,26 +163,16 @@ where
///
/// Other errors from `usb-device` may also be propagated.
pub fn read(&mut self, data: &mut [u8]) -> Result<usize> {
let buf = &mut self.read_buf;
let inner = &mut self.inner;

// Try to read a packet from the endpoint and write it into the buffer if it fits. Propagate
// errors except `WouldBlock`.
self.poll()?;

buf.write_all(inner.max_packet_size() as usize, |buf_data| {
match inner.read_packet(buf_data) {
Ok(c) => Ok(c),
Err(UsbError::WouldBlock) => Ok(0),
Err(err) => Err(err),
}
})?;

if buf.available_read() == 0 {
if self.read_buf.available_read() == 0 {
// No data available for reading.
return Err(UsbError::WouldBlock);
}

buf.read(data.len(), |buf_data| {
self.read_buf.read(data.len(), |buf_data| {
data[..buf_data.len()].copy_from_slice(buf_data);

Ok(buf_data.len())
Expand Down

0 comments on commit fb83286

Please sign in to comment.