Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix status response reading logic #4

Merged
merged 3 commits into from
Dec 7, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 14 additions & 17 deletions src/bus.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,20 @@ where
pub fn read_status_response(&mut self) -> Result<Response<ReadBuffer, WriteBuffer>, ReadError> {
let deadline = Instant::now() + self.read_timeout;
let stuffed_message_len = loop {
self.remove_garbage();

// The call to remove_garbage() removes all leading bytes that don't match a status header.
// So if there's enough bytes left, it's a status header.
if self.read_len > STATUS_HEADER_SIZE {
let read_buffer = &self.read_buffer.as_mut()[..self.read_len];
let body_len = read_buffer[5] as usize + read_buffer[6] as usize * 256;
let body_len = body_len - 2; // Length includes instruction and error fields, which is already included in STATUS_HEADER_SIZE too.

if self.read_len >= STATUS_HEADER_SIZE + body_len {
break STATUS_HEADER_SIZE + body_len;
}
}

if Instant::now() > deadline {
trace!("timeout reading status response, data in buffer: {:02X?}", &self.read_buffer.as_ref()[..self.read_len]);
return Err(std::io::ErrorKind::TimedOut.into());
Expand All @@ -173,23 +187,6 @@ where
}

self.read_len += new_data;
self.remove_garbage();

let read_buffer = &self.read_buffer.as_mut()[..self.read_len];
if !read_buffer.starts_with(&HEADER_PREFIX) {
continue;
}

if self.read_len < STATUS_HEADER_SIZE {
continue;
}

let body_len = read_buffer[5] as usize + read_buffer[6] as usize * 256;
let body_len = body_len - 2; // Length includes instruction and error fields, which is already included in STATUS_HEADER_SIZE too.

if self.read_len >= STATUS_HEADER_SIZE + body_len {
break STATUS_HEADER_SIZE + body_len;
}
};

let buffer = self.read_buffer.as_mut();
Expand Down
Loading