From c8cfc959383994b4373f96ff3ea4e51f67ae6897 Mon Sep 17 00:00:00 2001 From: torque Date: Tue, 30 Jul 2024 12:59:36 -0700 Subject: [PATCH] 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. --- src/YaesuController.zig | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/YaesuController.zig b/src/YaesuController.zig index 8b841a7..64628f6 100644 --- a/src/YaesuController.zig +++ b/src/YaesuController.zig @@ -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); } };