Skip to content

Commit 37ce1f5

Browse files
authored
Merge pull request hdoordt#4 from stephen-nordic/main
Workaround get_metadata() failing to parse response; make start_measurement_matching capable of 100000 samples/second
2 parents 6e4969a + da839f3 commit 37ce1f5

File tree

1 file changed

+29
-4
lines changed

1 file changed

+29
-4
lines changed

src/lib.rs

+29-4
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ pub mod cmd;
2222
pub mod measurement;
2323
pub mod types;
2424

25-
const SPS_MAX: usize = 90_000;
25+
const SPS_MAX: usize = 100_000;
2626

2727
#[derive(Error, Debug)]
2828
/// PPK2 communication or data parsing error.
@@ -97,12 +97,31 @@ impl Ppk2 {
9797
Ok(response)
9898
}
9999

100-
/// Get the device metadata.
101-
pub fn get_metadata(&mut self) -> Result<Metadata> {
100+
fn try_get_metadata(&mut self) -> Result<Metadata> {
102101
let response = self.send_command(Command::GetMetaData)?;
103102
Metadata::from_bytes(&response)
104103
}
105104

105+
/// Get the device metadata.
106+
pub fn get_metadata(&mut self) -> Result<Metadata> {
107+
let mut result: Result<Metadata> = Err(Error::Parse("Metadata".to_string()));
108+
109+
// Retry a few times, as the metadata command sometimes fails
110+
for _ in 0..3 {
111+
match self.try_get_metadata() {
112+
Ok(metadata) => {
113+
result = Ok(metadata);
114+
break;
115+
}
116+
Err(e) => {
117+
tracing::warn!("Error fetching metadata: {:?}. Retrying..", e);
118+
}
119+
}
120+
}
121+
122+
result
123+
}
124+
106125
/// Enable or disable the device power.
107126
pub fn set_device_power(&mut self, power: DevicePower) -> Result<()> {
108127
self.send_command(Command::DeviceRunningSet(power))?;
@@ -161,7 +180,13 @@ impl Ppk2 {
161180
.wait_while(lock.lock().unwrap(), |ready| !*ready)
162181
.unwrap();
163182

164-
let mut buf = [0u8; 1024];
183+
/* 4 bytes is the size of a single sample, and the PPK pushes 100,000 samples per second.
184+
Having size of `buf` at eg.1024 blocks port.read() until the buffer is full with 1024 bytes (128 samples).
185+
The measurement returned will be the average of the 128 samples. But we want to get every single sample when
186+
requested sps is 100,000. Hence, we set the buffer size to 4 bytes, and read the port in a loop,
187+
feeding the accumulator with the data.
188+
*/
189+
let mut buf = [0u8; 4];
165190
let mut measurement_buf = VecDeque::with_capacity(SPS_MAX);
166191
let mut missed = 0;
167192
loop {

0 commit comments

Comments
 (0)