Skip to content

Commit

Permalink
feat: windows polling
Browse files Browse the repository at this point in the history
  • Loading branch information
mochalins committed Sep 16, 2024
1 parent 580bd66 commit f33c09d
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions src/backend/windows.zig
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@ pub const Port = struct {
else => |e| return windows.unexpectedError(e),
}
}
errdefer self.close();

if (SetCommMask(self.file.?.handle, .{ .RXCHAR = true }) == 0) {
return windows.unexpectedError(windows.GetLastError());
}
}

pub fn close(self: *@This()) void {
Expand Down Expand Up @@ -123,6 +128,37 @@ pub const Port = struct {
}
}

pub fn poll(self: @This()) !bool {
if (self.file == null) return false;

var events: EventMask = undefined;

var overlapped: windows.OVERLAPPED = .{
.Internal = 0,
.InternalHigh = 0,
.DUMMYUNIONNAME = .{
.DUMMYSTRUCTNAME = .{
.Offset = 0,
.OffsetHigh = 0,
},
},
.hEvent = try windows.CreateEventEx(
null,
"",
windows.CREATE_EVENT_MANUAL_RESET,
windows.EVENT_ALL_ACCESS,
),
};
if (WaitCommEvent(self.file.?.handle, &events, &overlapped) == 0) {
switch (windows.GetLastError()) {
windows.Win32Error.IO_PENDING => return false,
else => |e| return windows.unexpectedError(e),
}
}

return events.RXCHAR;
}

pub fn reader(self: @This()) ?Reader {
return .{
.context = self.file orelse return null,
Expand Down Expand Up @@ -301,6 +337,17 @@ extern "kernel32" fn GetCommState(
lpDCB: *DCB,
) callconv(windows.WINAPI) windows.BOOL;

extern "kernel32" fn SetCommMask(
hFile: windows.HANDLE,
dwEvtMask: EventMask,
) callconv(windows.WINAPI) windows.BOOL;

extern "kernel32" fn WaitCommEvent(
hFile: windows.HANDLE,
lpEvtMask: *EventMask,
lpOverlapped: ?*windows.OVERLAPPED,
) callconv(windows.WINAPI) windows.BOOL;

extern "kernel32" fn PurgeComm(
hFile: windows.HANDLE,
dwFlags: packed struct(windows.DWORD) {
Expand All @@ -311,3 +358,16 @@ extern "kernel32" fn PurgeComm(
_: u28 = 0,
},
) callconv(windows.WINAPI) windows.BOOL;

const EventMask = packed struct(windows.DWORD) {
RXCHAR: bool = false,
RXFLAG: bool = false,
TXEMPTY: bool = false,
CTS: bool = false,
DSR: bool = false,
RLSD: bool = false,
BREAK: bool = false,
ERR: bool = false,
RING: bool = false,
_: u23 = 0,
};

0 comments on commit f33c09d

Please sign in to comment.