Skip to content
Snippets Groups Projects
Commit a4d9516b authored by Federico Lolli's avatar Federico Lolli
Browse files

removed time drift - now wait exact time (doesn't sleep but wait the precise instant)

parent 5384ec25
No related branches found
No related tags found
No related merge requests found
...@@ -72,33 +72,44 @@ fn main() { ...@@ -72,33 +72,44 @@ fn main() {
struct PacketSequence { struct PacketSequence {
packets: Vec<MavlinkPayloadFlightTM>, packets: Vec<MavlinkPayloadFlightTM>,
index: usize, index: usize,
last_timestamp: u64, delta_from_start: u64,
start_instant: Option<Instant>,
} }
impl From<Vec<MavlinkPayloadFlightTM>> for PacketSequence { impl From<Vec<MavlinkPayloadFlightTM>> for PacketSequence {
fn from(value: Vec<MavlinkPayloadFlightTM>) -> Self { fn from(value: Vec<MavlinkPayloadFlightTM>) -> Self {
let last_timestamp = value[0].timestamp; let delta_from_start = value[0].timestamp;
Self { Self {
packets: value, packets: value,
index: 0, index: 0,
last_timestamp, delta_from_start,
start_instant: None,
} }
} }
} }
impl PacketSequence { impl PacketSequence {
fn wait_next(&mut self) -> Option<&MavlinkPayloadFlightTM> { fn wait_next(&mut self) -> Option<&MavlinkPayloadFlightTM> {
let last = self.last_timestamp;
let to_sleep = self.packets[self.index].timestamp - last;
// return None if we reached the end of the sequence // return None if we reached the end of the sequence
if self.index == self.packets.len() { if self.index == self.packets.len() {
return None; return None;
} }
// sleep for the difference between the last timestamp and the current one // get time delta from the start
std::thread::sleep(Duration::from_millis(to_sleep / 1000)); let next_timestamp = self.packets[self.index].timestamp;
let time_delta = next_timestamp - self.delta_from_start;
// get the instant the first packet was sent or set it if it's the first packet
if let Some(start_inst) = self.start_instant {
// get the instant to wait until
let till = start_inst + Duration::from_micros(time_delta);
self.last_timestamp = self.packets[self.index].timestamp; // sleep for the difference between the last timestamp and the current one
std::thread::sleep(till - Instant::now());
} else {
// set the start instant
self.start_instant = Some(Instant::now());
}
self.index += 1; self.index += 1;
self.packets.get(self.index - 1) self.packets.get(self.index - 1)
} }
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment