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:
torque 2024-07-30 12:59:36 -07:00
parent a3b4ffc76d
commit c8cfc95938
Signed by: torque
SSH Key Fingerprint: SHA256:nCrXefBNo6EbjNSQhv0nXmEg/VuNq3sMF5b8zETw3Tk

View File

@ -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);
}
};