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 error handling if wrong number of bytes read #53

Merged
merged 2 commits into from
May 3, 2024
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
24 changes: 22 additions & 2 deletions src/device/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ macro_rules! reg_read_only {
id: u8,
) -> Result<$reg_type> {
let val = io.read(serial_port, id, $addr, size_of::<$reg_type>().try_into().unwrap())?;
check_response_size!(&val, $reg_type);
let val = $reg_type::from_le_bytes(val.try_into().unwrap());

Ok(val)
Expand All @@ -30,6 +31,7 @@ macro_rules! reg_read_only {
ids: &[u8],
) -> Result<Vec<$reg_type>> {
let val = io.sync_read(serial_port, ids, $addr, size_of::<$reg_type>().try_into().unwrap())?;
check_response_size!(&val, $reg_type);
let val = val
.iter()
.map(|v| $reg_type::from_le_bytes(v.as_slice().try_into().unwrap()))
Expand Down Expand Up @@ -91,8 +93,9 @@ macro_rules! reg_write_only_fb {
val: $reg_type,
) -> Result<$fb_type> {
let fb=io.write_fb(serial_port, id, $addr, &val.to_le_bytes())?;
let fb = $fb_type::from_le_bytes(fb.try_into().unwrap());
Ok(fb)
check_response_size!(&fb, $fb_type);
let fb = $fb_type::from_le_bytes(fb.try_into().unwrap());
Ok(fb)
}

#[doc = concat!("Sync write register *", stringify!($name), "* (addr: ", stringify!($addr), ", type: ", stringify!($reg_type), ")")]
Expand Down Expand Up @@ -133,6 +136,23 @@ macro_rules! reg_read_write_fb {
};
}

// Check if the response size is correct
// If not, return an error
// response is a Vec<u8>
macro_rules! check_response_size {
($response:expr, $reg_type:ty) => {{
let response = $response;
if response.len() != std::mem::size_of::<$reg_type>() {
let message = format!(
"Invalid response size, expected {} received {}",
std::mem::size_of::<$reg_type>(),
response.len()
);
return Err(message.into());
}
}};
}

pub mod l0_force_fan;
pub mod mx;
pub mod orbita2d_poulpe;
Expand Down
Loading