controller: fix bogus timer implementation
The previous version was using wall clock time for the timer because I am an idiot. During time syncs or possibly due to other reasons, this could jump backwards and cause an overflow. This obviously needed a monotonic clock source, and now it has one.
This commit is contained in:
parent
a3b4ffc76d
commit
c8cfc95938
@ -355,7 +355,7 @@ const Controller = struct {
|
||||
fn run(self: *Controller) !void {
|
||||
self.current_state = .initializing;
|
||||
|
||||
var timer: LoopTimer = .{ .interval_ns = config.controller.loop_interval_ns };
|
||||
var timer = LoopTimer.init(config.controller.loop_interval_ns);
|
||||
|
||||
while (timer.mark()) : (timer.sleep()) {
|
||||
self.updateFeedback() catch {
|
||||
@ -416,18 +416,22 @@ const Controller = struct {
|
||||
|
||||
pub const LoopTimer = struct {
|
||||
interval_ns: u64,
|
||||
timer: std.time.Timer,
|
||||
|
||||
start: i128 = 0,
|
||||
pub fn init(interval_ns: u64) LoopTimer {
|
||||
return .{
|
||||
.interval_ns = interval_ns,
|
||||
.timer = std.time.Timer.start() catch @panic("Could not create timer"),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn mark(self: *LoopTimer) bool {
|
||||
self.start = std.time.nanoTimestamp();
|
||||
self.timer.reset();
|
||||
return true;
|
||||
}
|
||||
|
||||
pub fn sleep(self: *LoopTimer) void {
|
||||
const now = std.time.nanoTimestamp();
|
||||
const elapsed: u64 = @intCast(now - self.start);
|
||||
|
||||
std.time.sleep(self.interval_ns - elapsed);
|
||||
const elapsed = self.timer.read();
|
||||
std.time.sleep(self.interval_ns -| elapsed);
|
||||
}
|
||||
};
|
||||
|
Loading…
x
Reference in New Issue
Block a user