diff --git a/src/main.zig b/src/main.zig index 806c219..e856191 100644 --- a/src/main.zig +++ b/src/main.zig @@ -18,6 +18,62 @@ pub const std_options: std.Options = .{ // these are all in degrees pub const AzEl = struct { az: f64, el: f64 }; +pub const Log = struct { + file: std.fs.File, + + pub fn init() !Log { + var buf: [64]u8 = undefined; + const now = std.time.milliTimestamp(); + const filename = try std.fmt.bufPrint(buf[0..], "rotint-{d}.eventlog", .{now}); + return .{ + .file = try std.fs.cwd().createFile(filename, .{ .exclusive = true }), + }; + } + + pub fn writeEvent(self: Log, event: Event) void { + var buf: [128]u8 = undefined; + var fbs = std.io.fixedBufferStream(buf[0..]); + const writer = fbs.writer().any(); + + const now = std.time.milliTimestamp(); + writer.print("{d},", .{now}) catch return; + event.write(writer) catch return; + writer.writeByte('\n') catch return; + self.file.writeAll(fbs.getWritten()) catch return; + } + + pub const Event = union(enum) { + offset_updated: AzEl, + request_updated: AzEl, + command_sent: AzEl, + position_updated: AzEl, + + pub fn designator(self: Event) []const u8 { + return switch (self) { + .offset_updated => "O", + .request_updated => "R", + .command_sent => "C", + .position_updated => "P", + }; + } + + pub fn write(self: Event, writer: std.io.AnyWriter) !void { + switch (self) { + .offset_updated, + .request_updated, + .command_sent, + .position_updated, + => |pos| { + try writer.print( + "{s},{d:.1},{d:.1}", + .{ self.designator(), pos.az, pos.el }, + ); + }, + } + } + }; +}; + pub const RotInt = struct { allocator: std.mem.Allocator, // TODO: associate timestamps with this somehow @@ -40,6 +96,8 @@ pub const RotInt = struct { poller: xev.Timer, poll_completion: xev.Completion = undefined, + log: Log = undefined, + pub const State = enum { initial, rotator_connected, @@ -50,6 +108,7 @@ pub const RotInt = struct { pub fn initInPlace(self: *RotInt) !void { self.server.rotint = self; self.rotator.rotint = self; + self.log = try Log.init(); const connect_addr = try std.net.Address.parseIp("127.0.0.1", 4533); try self.rotator.connect(self.loop, connect_addr); @@ -130,9 +189,11 @@ pub const RotInt = struct { }; switch (reply) { - .okay => {}, + .okay => if (self.last_command == .set_position) + self.log.writeEvent(.{ .command_sent = self.last_command.set_position }), .get_position => |pos| { self.current_posture = pos; + self.log.writeEvent(.{ .position_updated = pos }); if (self.state == .rotator_connected) self.stateEvent(.rotator_ready); self.draw() catch {}; }, @@ -165,6 +226,7 @@ pub const RotInt = struct { .set_position => |pos| { self.requested_posture = pos; self.server.respond(self.loop, .okay); + self.log.writeEvent(.{ .request_updated = pos }); self.draw() catch {}; }, @@ -261,6 +323,7 @@ pub const RotInt = struct { self.offsets.az += delta.az; self.offsets.el += delta.el; + self.log.writeEvent(.{ .offset_updated = self.offsets }); self.draw() catch { self.warn("draw failure", .{}); };