From 0bc2e226cf985fc053ff59323866212ae9ddbce3 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Tue, 10 Nov 2026 17:48:04 +0100 Subject: [PATCH 01/28] usb.types.Len -> usb.types.PacketLen --- core/src/core/usb.zig | 18 +++++++++--------- core/src/core/usb/descriptor.zig | 6 +++--- core/src/core/usb/drivers/CDC.zig | 10 +++++----- core/src/core/usb/drivers/EchoExample.zig | 2 +- core/src/core/usb/drivers/hid.zig | 2 +- core/src/core/usb/types.zig | 7 +++++-- port/nordic/nrf5x/src/hal/usbd.zig | 8 ++++---- port/raspberrypi/rp2xxx/src/hal/usb.zig | 10 +++++----- port/wch/ch32v/src/hals/usbd.zig | 6 +++--- port/wch/ch32v/src/hals/usbfs.zig | 10 +++++----- port/wch/ch32v/src/hals/usbhs.zig | 10 +++++----- 11 files changed, 46 insertions(+), 43 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index a21e9e554..d534e24e0 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -84,9 +84,9 @@ pub fn DescriptorCreateResult(Descriptor: type) type { /// Any device implementation used with DeviceController must implement these functions pub const DeviceInterface = struct { pub const VTable = struct { - ep_writev: *const fn (*DeviceInterface, types.Endpoint.Num, []const []const u8) types.Len, - ep_readv: *const fn (*DeviceInterface, types.Endpoint.Num, []const []u8) types.Len, - ep_listen: *const fn (*DeviceInterface, types.Endpoint.Num, types.Len) void, + ep_writev: *const fn (*DeviceInterface, types.Endpoint.Num, []const []const u8) types.PacketLength, + ep_readv: *const fn (*DeviceInterface, types.Endpoint.Num, []const []u8) types.PacketLength, + ep_listen: *const fn (*DeviceInterface, types.Endpoint.Num, types.PacketLength) void, ep_open: *const fn (*DeviceInterface, *const descriptor.Endpoint) void, set_address: *const fn (*DeviceInterface, u7) void, }; @@ -94,7 +94,7 @@ pub const DeviceInterface = struct { vtable: *const VTable, /// Called by drivers to send a packet. - pub fn ep_writev(self: *@This(), ep_num: types.Endpoint.Num, data: []const []const u8) types.Len { + pub fn ep_writev(self: *@This(), ep_num: types.Endpoint.Num, data: []const []const u8) types.PacketLength { return self.vtable.ep_writev(self, ep_num, data); } @@ -106,13 +106,13 @@ pub const DeviceInterface = struct { /// Called by drivers to retrieve a received packet. /// Must be called exactly once for each packet. /// Buffers in `data` must collectively be long enough to fit the whole packet. - pub fn ep_readv(self: *@This(), ep_num: types.Endpoint.Num, data: []const []u8) types.Len { + pub fn ep_readv(self: *@This(), ep_num: types.Endpoint.Num, data: []const []u8) types.PacketLength { return self.vtable.ep_readv(self, ep_num, data); } /// Called by drivers to report readiness to receive up to `len` bytes. /// After being called it may not be called again until a packet is received. - pub fn ep_listen(self: *@This(), ep_num: types.Endpoint.Num, len: types.Len) void { + pub fn ep_listen(self: *@This(), ep_num: types.Endpoint.Num, len: types.PacketLength) void { return self.vtable.ep_listen(self, ep_num, len); } @@ -174,8 +174,8 @@ pub const Config = struct { assert(param_types.len == 3); // The first must be a DescriptorAllocator assert(param_types[0] == *DescriptorAllocator); - // The second is usb.types.Len - assert(param_types[1] == types.Len); + // The second is usb.types.PacketLength + assert(param_types[1] == types.PacketLength); // And save the type of the third field_types[i] = param_types[2].?; } @@ -198,7 +198,7 @@ pub const Config = struct { /// Serial number string. serial: []const u8, /// Largest packet length the hardware supports. Must be a power of 2 and at least 8. - max_supported_packet_size: types.Len, + max_supported_packet_size: types.PacketLength, /// Currently only a single configuration is supported. configurations: []const Configuration, /// Only use either IN or OUT on each endpoint. Useful for debugging. diff --git a/core/src/core/usb/descriptor.zig b/core/src/core/usb/descriptor.zig index 581e68a70..ce649e296 100644 --- a/core/src/core/usb/descriptor.zig +++ b/core/src/core/usb/descriptor.zig @@ -212,7 +212,7 @@ pub const Endpoint = extern struct { /// currently support) in milliseconds. interval: u8, - pub fn control(ep: types.Endpoint, max_packet_size: types.Len) @This() { + pub fn control(ep: types.Endpoint, max_packet_size: types.PacketLength) @This() { return .{ .endpoint = ep, .attributes = .{ .transfer_type = .Control, .usage = .data }, @@ -221,7 +221,7 @@ pub const Endpoint = extern struct { }; } - pub fn bulk(ep: types.Endpoint, max_packet_size: types.Len) @This() { + pub fn bulk(ep: types.Endpoint, max_packet_size: types.PacketLength) @This() { return .{ .endpoint = ep, .attributes = .{ .transfer_type = .Bulk, .usage = .data }, @@ -230,7 +230,7 @@ pub const Endpoint = extern struct { }; } - pub fn interrupt(ep: types.Endpoint, max_packet_size: types.Len, poll_interval: u8) @This() { + pub fn interrupt(ep: types.Endpoint, max_packet_size: types.PacketLength, poll_interval: u8) @This() { return .{ .endpoint = ep, .attributes = .{ .transfer_type = .Interrupt, .usage = .data }, diff --git a/core/src/core/usb/drivers/CDC.zig b/core/src/core/usb/drivers/CDC.zig index f6ab55abb..3b82f790d 100644 --- a/core/src/core/usb/drivers/CDC.zig +++ b/core/src/core/usb/drivers/CDC.zig @@ -85,7 +85,7 @@ pub const Descriptor = extern struct { /// through this function is preferred to making the whole driver generic. pub fn create( alloc: *usb.DescriptorAllocator, - max_supported_packet_size: usb.types.Len, + max_supported_packet_size: usb.types.PacketLength, strings: Strings, ) usb.DescriptorCreateResult(@This()) { // Endpoint and interface numbers are allocated through the `alloc` parameter, @@ -165,15 +165,15 @@ line_coding: LineCoding align(4), notifi_ready: std.atomic.Value(bool), rx_data: []u8, -rx_seek: usb.types.Len, -rx_end: usb.types.Len, +rx_seek: usb.types.PacketLength, +rx_end: usb.types.PacketLength, rx_ready: std.atomic.Value(bool), tx_data: []u8, -tx_end: usb.types.Len, +tx_end: usb.types.PacketLength, tx_ready: std.atomic.Value(bool), -pub fn available(self: *@This()) usb.types.Len { +pub fn available(self: *@This()) usb.types.PacketLength { return self.rx_end - self.rx_seek; } diff --git a/core/src/core/usb/drivers/EchoExample.zig b/core/src/core/usb/drivers/EchoExample.zig index f78a4bc6f..a4fd8b19f 100644 --- a/core/src/core/usb/drivers/EchoExample.zig +++ b/core/src/core/usb/drivers/EchoExample.zig @@ -19,7 +19,7 @@ pub const Descriptor = extern struct { /// through this function is preffered to making the whole driver generic. pub fn create( alloc: *usb.DescriptorAllocator, - max_supported_packet_size: usb.types.Len, + max_supported_packet_size: usb.types.PacketLength, itf_string: []const u8, ) usb.DescriptorCreateResult(@This()) { return .{ diff --git a/core/src/core/usb/drivers/hid.zig b/core/src/core/usb/drivers/hid.zig index 49205c845..e00af333d 100644 --- a/core/src/core/usb/drivers/hid.zig +++ b/core/src/core/usb/drivers/hid.zig @@ -337,7 +337,7 @@ pub fn InterruptDriver(options: InterruptDriverOptions) type { pub fn create( alloc: *usb.DescriptorAllocator, - max_supported_packet_size: usb.types.Len, + max_supported_packet_size: usb.types.PacketLength, desc_options: Options, ) usb.DescriptorCreateResult(@This()) { assert(@sizeOf(InReport) <= max_supported_packet_size); diff --git a/core/src/core/usb/types.zig b/core/src/core/usb/types.zig index 658b3f706..8ba7f36fd 100644 --- a/core/src/core/usb/types.zig +++ b/core/src/core/usb/types.zig @@ -480,5 +480,8 @@ pub const Version = extern struct { } }; -/// Represents packet length. -pub const Len = u11; +/// Represents physical packet length. +pub const PacketLength = u11; + +/// Deprecated; use `PacketLength`. +pub const Len = PacketLength; diff --git a/port/nordic/nrf5x/src/hal/usbd.zig b/port/nordic/nrf5x/src/hal/usbd.zig index fa6583410..711ecd1f7 100644 --- a/port/nordic/nrf5x/src/hal/usbd.zig +++ b/port/nordic/nrf5x/src/hal/usbd.zig @@ -263,7 +263,7 @@ pub const USBD = struct { itf: *usb.DeviceInterface, ep_num: usb.types.Endpoint.Num, data: []const []const u8, - ) usb.types.Len { + ) usb.types.PacketLength { const self: *Self = @fieldParentPtr("interface", itf); log.debug("ep_writev {t}: ({} bytes) {X} ({s})", .{ ep_num, data[0].len, data[0], data[0] }); @@ -283,7 +283,7 @@ pub const USBD = struct { scratch_slice = scratch_slice[len..]; } - const len: usb.types.Len = @intCast(scratch_cap - scratch_slice.len); + const len: usb.types.PacketLength = @intCast(scratch_cap - scratch_slice.len); // Prepare DMA transfer peripherals.USBD.EPIN[i].PTR.write_raw(@intFromPtr(scratch)); @@ -323,7 +323,7 @@ pub const USBD = struct { itf: *usb.DeviceInterface, ep_num: usb.types.Endpoint.Num, data: []const []u8, - ) usb.types.Len { + ) usb.types.PacketLength { var total_len: usize = data[0].len; for (data[1..]) |d| total_len += d.len; log.debug("ep_readv {t}: ({} bytes)", .{ ep_num, total_len }); @@ -362,7 +362,7 @@ pub const USBD = struct { fn ep_listen( _: *usb.DeviceInterface, ep_num: usb.types.Endpoint.Num, - len: usb.types.Len, + len: usb.types.PacketLength, ) void { log.debug("ep_listen {t}: ({} bytes)", .{ ep_num, len }); diff --git a/port/raspberrypi/rp2xxx/src/hal/usb.zig b/port/raspberrypi/rp2xxx/src/hal/usb.zig index 517cfe23a..4593e7d66 100644 --- a/port/raspberrypi/rp2xxx/src/hal/usb.zig +++ b/port/raspberrypi/rp2xxx/src/hal/usb.zig @@ -268,7 +268,7 @@ pub fn Polled(config: Config) type { itf: *usb.DeviceInterface, ep_num: usb.types.Endpoint.Num, data: []const []const u8, - ) usb.types.Len { + ) usb.types.PacketLength { log.debug("writev {t} {}: {any}", .{ ep_num, data[0].len, data[0] }); const self: *@This() = @fieldParentPtr("interface", itf); @@ -283,7 +283,7 @@ pub fn Polled(config: Config) type { hw_buf = hw_buf[len..]; } - const len: usb.types.Len = @intCast(ep.data_buffer.len - hw_buf.len); + const len: usb.types.PacketLength = @intCast(ep.data_buffer.len - hw_buf.len); var bufctrl = bufctrl_ptr.read(); assert(bufctrl.AVAILABLE_0 == 0); @@ -314,7 +314,7 @@ pub fn Polled(config: Config) type { itf: *usb.DeviceInterface, ep_num: usb.types.Endpoint.Num, data: []const []u8, - ) usb.types.Len { + ) usb.types.PacketLength { var total_len: usize = data[0].len; for (data[1..]) |d| total_len += d.len; log.debug("readv {t} {}", .{ ep_num, total_len }); @@ -340,7 +340,7 @@ pub fn Polled(config: Config) type { fn ep_listen( itf: *usb.DeviceInterface, ep_num: usb.types.Endpoint.Num, - len: usb.types.Len, + len: usb.types.PacketLength, ) void { log.debug("listen {t} {}", .{ ep_num, len }); @@ -454,7 +454,7 @@ pub fn ResetDriver(bootsel_activity_led: ?u5, interface_disable_mask: u32) type pub fn create( alloc: *usb.DescriptorAllocator, - _: usb.types.Len, + _: usb.types.PacketLength, interface_str: []const u8, ) usb.DescriptorCreateResult(@This()) { return .{ .descriptor = .{ .reset_interface = .{ diff --git a/port/wch/ch32v/src/hals/usbd.zig b/port/wch/ch32v/src/hals/usbd.zig index 910d433ad..149c00450 100644 --- a/port/wch/ch32v/src/hals/usbd.zig +++ b/port/wch/ch32v/src/hals/usbd.zig @@ -666,7 +666,7 @@ pub fn Polled(comptime setup: Setup, comptime cfg: Config) type { } } - fn ep_listen(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, len: types.Len) void { + fn ep_listen(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, len: types.PacketLength) void { log.debug("ep_listen ep{} len={}", .{ ep_num, len }); const self: *Self = @fieldParentPtr("interface", itf); @@ -696,7 +696,7 @@ pub fn Polled(comptime setup: Setup, comptime cfg: Config) type { Epr.set_stat_rx(ep_i, .valid); } - fn ep_readv(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, data: []const []u8) types.Len { + fn ep_readv(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, data: []const []u8) types.PacketLength { const self: *Self = @fieldParentPtr("interface", itf); const ep_i: u4 = epn(ep_num); const st_out = self.st(ep_num, .out); @@ -727,7 +727,7 @@ pub fn Polled(comptime setup: Setup, comptime cfg: Config) type { return @intCast(copied); } - fn ep_writev(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, vec: []const []const u8) types.Len { + fn ep_writev(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, vec: []const []const u8) types.PacketLength { log.debug("ep_writev called for ep{} with {} chunks", .{ ep_num, vec.len }); const self: *Self = @fieldParentPtr("interface", itf); assert(vec.len > 0); diff --git a/port/wch/ch32v/src/hals/usbfs.zig b/port/wch/ch32v/src/hals/usbfs.zig index 9ebf31670..f45596d3e 100644 --- a/port/wch/ch32v/src/hals/usbfs.zig +++ b/port/wch/ch32v/src/hals/usbfs.zig @@ -457,7 +457,7 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { } } - fn ep_listen(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, len: types.Len) void { + fn ep_listen(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, len: types.PacketLength) void { log.debug("ep_listen ep{} len={}", .{ ep_num, len }); const self: *Self = @fieldParentPtr("interface", itf); @@ -489,7 +489,7 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { set_rx_ctrl(ep_i, RES_ACK, current_rx_tog(ep_i), false); } - fn ep_readv(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, data: []const []u8) types.Len { + fn ep_readv(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, data: []const []u8) types.PacketLength { const self: *Self = @fieldParentPtr("interface", itf); const st_out = self.st(ep_num, .out); @@ -514,10 +514,10 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { } // Driver is responsible for re-arming via ep_listen(). - return @as(types.Len, @intCast(copied)); + return @intCast(copied); } - fn ep_writev(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, vec: []const []const u8) types.Len { + fn ep_writev(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, vec: []const []const u8) types.PacketLength { log.debug("ep_writev called for ep{} with {} chunks", .{ ep_num, vec.len }); const self: *Self = @fieldParentPtr("interface", itf); assert(vec.len > 0); @@ -549,7 +549,7 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { set_tx_ctrl(ep_i, RES_ACK, current_tx_tog(ep_i), false); // For ZLP ACK, usb.DeviceInterface.ep_ack() expects ep_writev() returns 0. - return @as(types.Len, @intCast(w)); + return @intCast(w); } // ---- HW init --------------------------------------------------------- diff --git a/port/wch/ch32v/src/hals/usbhs.zig b/port/wch/ch32v/src/hals/usbhs.zig index a1ef04ccc..ec13ba575 100644 --- a/port/wch/ch32v/src/hals/usbhs.zig +++ b/port/wch/ch32v/src/hals/usbhs.zig @@ -522,7 +522,7 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { log.debug("ep_open completed for ep{}", .{ep_i}); } - fn ep_listen(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, len: types.Len) void { + fn ep_listen(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, len: types.PacketLength) void { log.info("ep_listen called for ep{} len={}", .{ ep_num, len }); const self: *Self = @fieldParentPtr("interface", itf); @@ -558,7 +558,7 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { set_rx_ctrl(ep_i, RES_ACK, current_rx_tog(ep_i), false); } - fn ep_readv(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, data: []const []u8) types.Len { + fn ep_readv(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, data: []const []u8) types.PacketLength { const self: *Self = @fieldParentPtr("interface", itf); const st_out = self.st(ep_num, .out); @@ -583,10 +583,10 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { } // Driver is responsible for re-arming via ep_listen(). - return @as(types.Len, @intCast(copied)); + return @intCast(copied); } - fn ep_writev(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, vec: []const []const u8) types.Len { + fn ep_writev(itf: *usb.DeviceInterface, ep_num: types.Endpoint.Num, vec: []const []const u8) types.PacketLength { const self: *Self = @fieldParentPtr("interface", itf); assert(vec.len > 0); @@ -619,7 +619,7 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { set_tx_ctrl(ep_i, RES_ACK, current_tx_tog(ep_i), false); // For ZLP ACK, usb.DeviceInterface.ep_ack() expects ep_writev() returns 0. - return @as(types.Len, @intCast(w)); + return @intCast(w); } // ---- HW init --------------------------------------------------------- From d8333e1225de5946e5c07eb8a235fbde6015f2df Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Tue, 10 Nov 2026 17:48:12 +0100 Subject: [PATCH 02/28] Reduce pointless return @as(...); --- core/src/allocator.zig | 2 +- core/src/core/arm_semihosting.zig | 2 +- drivers/src/base/Digital_IO.zig | 2 +- drivers/src/root.zig | 8 ++++---- port/espressif/esp/src/hal/gpio.zig | 2 +- port/nordic/nrf5x/src/hal/i2c.zig | 2 +- port/nordic/nrf5x/src/hal/i2cdma.zig | 2 +- port/nordic/nrf5x/src/hal/spim.zig | 2 +- port/raspberrypi/rp2xxx/src/hal/adc.zig | 4 ++-- port/raspberrypi/rp2xxx/src/hal/i2c.zig | 7 ++++--- port/raspberrypi/rp2xxx/src/hal/pio.zig | 2 +- port/raspberrypi/rp2xxx/src/hal/pio/common.zig | 2 +- port/raspberrypi/rp2xxx/src/hal/pwm.zig | 2 +- port/raspberrypi/rp2xxx/src/hal/spi.zig | 7 ++++--- port/raspberrypi/rp2xxx/src/hal/usb.zig | 2 +- port/stmicro/stm32/src/hals/STM32F407.zig | 4 ++-- port/stmicro/stm32/src/hals/common/uart_v3.zig | 2 +- 17 files changed, 28 insertions(+), 26 deletions(-) diff --git a/core/src/allocator.zig b/core/src/allocator.zig index a9a915a9a..33d4522e1 100644 --- a/core/src/allocator.zig +++ b/core/src/allocator.zig @@ -418,7 +418,7 @@ pub const Chunk = extern struct { }); // Otherwise, just go for it. - return @as(*Chunk, @ptrCast(@alignCast(data_slice.ptr - header_size))); + return @ptrCast(@alignCast(data_slice.ptr - header_size)); } /// Return a data slice that maps the chunk's memory the user can use. diff --git a/core/src/core/arm_semihosting.zig b/core/src/core/arm_semihosting.zig index 73e121e65..52a840757 100644 --- a/core/src/core/arm_semihosting.zig +++ b/core/src/core/arm_semihosting.zig @@ -216,7 +216,7 @@ pub const Time = struct { ///return the host time in epoch pub fn system_time() usize { - return @as(usize, @bitCast(sys_time())); + return @bitCast(sys_time()); } ///return the corrent tick counter value in centiseconds pub fn absolute() TimeError!usize { diff --git a/drivers/src/base/Digital_IO.zig b/drivers/src/base/Digital_IO.zig index ffda44901..eea8218a9 100644 --- a/drivers/src/base/Digital_IO.zig +++ b/drivers/src/base/Digital_IO.zig @@ -29,7 +29,7 @@ pub const State = enum(u1) { high = 1, pub inline fn invert(state: State) State { - return @as(State, @fromBackingInt(~@backingInt(state))); + return @fromBackingInt(~@backingInt(state)); } pub inline fn value(state: State) u1 { diff --git a/drivers/src/root.zig b/drivers/src/root.zig index b5ec2b2f3..67c19aaf8 100644 --- a/drivers/src/root.zig +++ b/drivers/src/root.zig @@ -106,7 +106,7 @@ pub const time = struct { _, pub fn from_us(us: u64) Absolute { - return @as(Absolute, @fromBackingInt(us)); + return @fromBackingInt(us); } pub fn to_us(abs: Absolute) u64 { @@ -136,7 +136,7 @@ pub const time = struct { _, pub fn from_us(us: u64) Duration { - return @as(Duration, @fromBackingInt(us)); + return @fromBackingInt(us); } pub fn from_ms(ms: u64) Duration { @@ -210,11 +210,11 @@ pub const time = struct { }; pub fn make_timeout(since: Absolute, timeout: Duration) Absolute { - return @as(Absolute, @fromBackingInt(since.to_us() + timeout.to_us())); + return @fromBackingInt(since.to_us() + timeout.to_us()); } pub fn make_timeout_us(since: Absolute, timeout_us: u64) Absolute { - return @as(Absolute, @fromBackingInt(since.to_us() + timeout_us)); + return @fromBackingInt(since.to_us() + timeout_us); } }; diff --git a/port/espressif/esp/src/hal/gpio.zig b/port/espressif/esp/src/hal/gpio.zig index cb6a643fa..889ae753a 100644 --- a/port/espressif/esp/src/hal/gpio.zig +++ b/port/espressif/esp/src/hal/gpio.zig @@ -218,7 +218,7 @@ pub const Mask = enum(u22) { pub fn num(n: u5) Pin { std.debug.assert(n < 22); - return @as(Pin, @fromBackingInt(n)); + return @fromBackingInt(n); } pub const Pin = enum(u5) { diff --git a/port/nordic/nrf5x/src/hal/i2c.zig b/port/nordic/nrf5x/src/hal/i2c.zig index 44c8d9edb..d5f2b2aee 100644 --- a/port/nordic/nrf5x/src/hal/i2c.zig +++ b/port/nordic/nrf5x/src/hal/i2c.zig @@ -38,7 +38,7 @@ pub const AddressError = drivers.I2C_Device.Address.Error; pub const Error = drivers.I2C_Device.Error || error{Overrun}; pub fn num(n: u1) I2C { - return @as(I2C, @fromBackingInt(n)); + return @fromBackingInt(n); } pub const I2C = enum(u1) { diff --git a/port/nordic/nrf5x/src/hal/i2cdma.zig b/port/nordic/nrf5x/src/hal/i2cdma.zig index 0045ef7c6..4af21ba96 100644 --- a/port/nordic/nrf5x/src/hal/i2cdma.zig +++ b/port/nordic/nrf5x/src/hal/i2cdma.zig @@ -46,7 +46,7 @@ pub const Error = drivers.I2C_Device.Error || error{ /// Create an I2C instance from a peripheral number (0 or 1). pub fn num(n: u1) I2C { - return @as(I2C, @fromBackingInt(n)); + return @fromBackingInt(n); } pub const I2C = enum(u1) { diff --git a/port/nordic/nrf5x/src/hal/spim.zig b/port/nordic/nrf5x/src/hal/spim.zig index f5553537e..51a81b6ce 100644 --- a/port/nordic/nrf5x/src/hal/spim.zig +++ b/port/nordic/nrf5x/src/hal/spim.zig @@ -59,7 +59,7 @@ pub const TransactionError = error{ }; pub fn num(n: u2) SPIM { - return @as(SPIM, @fromBackingInt(n)); + return @fromBackingInt(n); } pub const SPIM = enum(u1) { diff --git a/port/raspberrypi/rp2xxx/src/hal/adc.zig b/port/raspberrypi/rp2xxx/src/hal/adc.zig index 19e3b5754..a091dcca6 100644 --- a/port/raspberrypi/rp2xxx/src/hal/adc.zig +++ b/port/raspberrypi/rp2xxx/src/hal/adc.zig @@ -19,7 +19,7 @@ pub const Error = error{ /// temp_sensor is not valid because you can refer to it by name. pub fn input(n: u2) Input { - return @as(Input, @fromBackingInt(n)); + return @fromBackingInt(n); } /// Enable the ADC controller. @@ -81,7 +81,7 @@ pub fn select_input(in: Input) void { /// Get the currently selected analog input. pub fn get_selected_input() Input { const cs = ADC.SC.read(); - return @as(Input, @fromBackingInt(cs.AINSEL)); + return @fromBackingInt(cs.AINSEL); } /// For RP2040 and RP2350A, the values are: diff --git a/port/raspberrypi/rp2xxx/src/hal/i2c.zig b/port/raspberrypi/rp2xxx/src/hal/i2c.zig index 97314ebd9..aad0c0a11 100644 --- a/port/raspberrypi/rp2xxx/src/hal/i2c.zig +++ b/port/raspberrypi/rp2xxx/src/hal/i2c.zig @@ -158,11 +158,12 @@ test "i2c.translate_baudrate" { } pub const instance = struct { - pub const I2C0: I2C = @as(I2C, @fromBackingInt(0)); - pub const I2C1: I2C = @as(I2C, @fromBackingInt(1)); pub fn num(instance_number: u1) I2C { - return @as(I2C, @fromBackingInt(instance_number)); + return @fromBackingInt(instance_number); } + + pub const I2C0 = num(0); + pub const I2C1 = num(1); }; /// An API for interacting with the RP2040's I2C driver. diff --git a/port/raspberrypi/rp2xxx/src/hal/pio.zig b/port/raspberrypi/rp2xxx/src/hal/pio.zig index 3287ad962..bd511d2d3 100644 --- a/port/raspberrypi/rp2xxx/src/hal/pio.zig +++ b/port/raspberrypi/rp2xxx/src/hal/pio.zig @@ -37,7 +37,7 @@ pub fn num(n: u2) Pio { }, } - return @as(Pio, @fromBackingInt(@intCast(n))); + return @fromBackingInt(@intCast(n)); } pub const Pio = chip_specific.Pio; diff --git a/port/raspberrypi/rp2xxx/src/hal/pio/common.zig b/port/raspberrypi/rp2xxx/src/hal/pio/common.zig index dfa5a0102..34dee469a 100644 --- a/port/raspberrypi/rp2xxx/src/hal/pio/common.zig +++ b/port/raspberrypi/rp2xxx/src/hal/pio/common.zig @@ -122,7 +122,7 @@ pub fn PioImpl(EnumType: type, chip: Chip) type { return struct { pub fn get_instruction_memory(self: EnumType) *volatile [32]u32 { const regs = self.get_regs(); - return @as(*volatile [32]u32, @ptrCast(®s.INSTR_MEM0)); + return @ptrCast(®s.INSTR_MEM0); } pub fn can_add_program_at_offset(self: EnumType, program: Program, offset: u5) bool { diff --git a/port/raspberrypi/rp2xxx/src/hal/pwm.zig b/port/raspberrypi/rp2xxx/src/hal/pwm.zig index 169d2e7fe..3c6ceb341 100644 --- a/port/raspberrypi/rp2xxx/src/hal/pwm.zig +++ b/port/raspberrypi/rp2xxx/src/hal/pwm.zig @@ -12,7 +12,7 @@ fn get_regs(slice: u32) *volatile Regs { @import("std").debug.assert(slice < if (has_rp2350b) 12 else 8); const PwmType = microzig.chip.types.peripherals.PWM; const reg_diff = comptime @offsetOf(PwmType, "CH1_CSR") - @offsetOf(PwmType, "CH0_CSR"); - return @as(*volatile Regs, @ptrFromInt(@intFromPtr(PWM) + reg_diff * slice)); + return @ptrFromInt(@intFromPtr(PWM) + reg_diff * slice); } pub const Channel = enum(u1) { a, b }; diff --git a/port/raspberrypi/rp2xxx/src/hal/spi.zig b/port/raspberrypi/rp2xxx/src/hal/spi.zig index 916beb452..6ac9c2cf4 100644 --- a/port/raspberrypi/rp2xxx/src/hal/spi.zig +++ b/port/raspberrypi/rp2xxx/src/hal/spi.zig @@ -58,11 +58,12 @@ pub const Config = struct { }; pub const instance = struct { - pub const SPI0: SPI = @as(SPI, @fromBackingInt(0)); - pub const SPI1: SPI = @as(SPI, @fromBackingInt(1)); pub fn num(instance_number: u1) SPI { - return @as(SPI, @fromBackingInt(instance_number)); + return @fromBackingInt(instance_number); } + + pub const SPI0 = num(0); + pub const SPI1 = num(1); }; pub const ConfigError = error{ diff --git a/port/raspberrypi/rp2xxx/src/hal/usb.zig b/port/raspberrypi/rp2xxx/src/hal/usb.zig index 4593e7d66..8098e1c47 100644 --- a/port/raspberrypi/rp2xxx/src/hal/usb.zig +++ b/port/raspberrypi/rp2xxx/src/hal/usb.zig @@ -46,7 +46,7 @@ const rp2xxx_buffers = struct { fn data_offset(ep_data_buffer: []u8) u16 { const buf_base = @intFromPtr(&ep_data_buffer[0]); const dpram_base = @intFromPtr(peripherals.USB_DPRAM); - return @as(u16, @intCast(buf_base - dpram_base)); + return @intCast(buf_base - dpram_base); } }; diff --git a/port/stmicro/stm32/src/hals/STM32F407.zig b/port/stmicro/stm32/src/hals/STM32F407.zig index b1b802cf7..93dd5643c 100644 --- a/port/stmicro/stm32/src/hals/STM32F407.zig +++ b/port/stmicro/stm32/src/hals/STM32F407.zig @@ -120,7 +120,7 @@ pub const gpio = struct { pub fn read(comptime pin: type) microzig.gpio.State { const idr_reg = pin.gpio_port.IDR; const reg_value = @field(idr_reg.read(), "IDR" ++ pin.suffix); // TODO extract to getRegField()? - return @as(microzig.gpio.State, @fromBackingInt(reg_value)); + return @fromBackingInt(reg_value); } pub fn write(comptime pin: type, state: microzig.gpio.State) void { @@ -355,7 +355,7 @@ pub fn Uart(comptime index: usize, comptime pins: microzig.uart.Pins) type { pub fn rx(self: Self) u8 { while (!self.can_read()) {} // Wait till the data is received const data_with_parity_bit: u9 = @field(peripherals, usart_name).DR.read(); - return @as(u8, @intCast(data_with_parity_bit & self.parity_read_mask)); + return @intCast(data_with_parity_bit & self.parity_read_mask); } }; } diff --git a/port/stmicro/stm32/src/hals/common/uart_v3.zig b/port/stmicro/stm32/src/hals/common/uart_v3.zig index b1ff8050a..aa4a77e72 100644 --- a/port/stmicro/stm32/src/hals/common/uart_v3.zig +++ b/port/stmicro/stm32/src/hals/common/uart_v3.zig @@ -165,7 +165,7 @@ pub fn Uart(comptime index: UART_Type) type { pub fn rx(self: Self) u8 { while (!self.can_read()) {} // Wait till the data is received const data_with_parity_bit: u9 = regs.RDR.read().RDR; - return @as(u8, @intCast(data_with_parity_bit & self.read_mask())); + return @intCast(data_with_parity_bit & self.read_mask()); } fn writer_fn(self: *Self, buffer: []const u8) error{}!usize { From 722e0322ace564732fefce90e2d607bf32c685da Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Tue, 10 Nov 2026 17:48:28 +0100 Subject: [PATCH 03/28] USB-specific little-endian LeInt --- core/src/core/usb/descriptor.zig | 16 +++++++--------- core/src/core/usb/drivers/CDC.zig | 5 +---- core/src/core/usb/types.zig | 14 ++++++++++---- 3 files changed, 18 insertions(+), 17 deletions(-) diff --git a/core/src/core/usb/descriptor.zig b/core/src/core/usb/descriptor.zig index ce649e296..4c9b296df 100644 --- a/core/src/core/usb/descriptor.zig +++ b/core/src/core/usb/descriptor.zig @@ -1,7 +1,5 @@ const std = @import("std"); -const EndianInt = @import("../mem.zig").EndianInt; - const types = @import("types.zig"); const assert = std.debug.assert; @@ -69,9 +67,9 @@ pub const Device = extern struct { /// Maximum length of data this device can move. max_packet_size0: u8, /// ID of product vendor. - vendor: EndianInt(u16, .little) align(1), + vendor: types.LeInt(u16) align(1), /// ID of product. - product: EndianInt(u16, .little) align(1), + product: types.LeInt(u16) align(1), /// Device version number as Binary Coded Decimal. bcd_device: types.Version, /// Index of manufacturer name in string descriptor table. @@ -130,7 +128,7 @@ pub const Configuration = extern struct { /// Total length of all descriptors in this configuration, concatenated. /// This will include this descriptor, plus at least one interface /// descriptor, plus each interface descriptor's endpoint descriptors. - total_length: EndianInt(u16, .little) align(1), + total_length: types.LeInt(u16) align(1), /// Number of interface descriptors in this configuration. num_interfaces: u8, /// Number to use when requesting this configuration via a @@ -157,7 +155,7 @@ pub const String = struct { const ret: *const extern struct { length: u8 = @sizeOf(@This()), descriptor_type: Type = .string, - lang: EndianInt(u16, .little) align(1), + lang: types.LeInt(u16) align(1), } = comptime &.{ .lang = .from(@backingInt(lang)) }; return .{ .data = std.mem.asBytes(ret) }; } @@ -207,7 +205,7 @@ pub const Endpoint = extern struct { /// control the transfer type using the values from `TransferType`. attributes: Attributes, /// Maximum packet size this endpoint can accept/produce. - max_packet_size: EndianInt(u16, .little) align(1), + max_packet_size: types.LeInt(u16) align(1), /// Interval for polling interrupt/isochronous endpoints (which we don't /// currently support) in milliseconds. interval: u8, @@ -300,7 +298,7 @@ pub const BOS = struct { const header: []const u8 = std.mem.asBytes(&extern struct { length: u8 = @sizeOf(@This()), descriptor_type: Type = .bos, - total_length: EndianInt(u16, .little) align(1) = .from(@sizeOf(@This()) + data.len), + total_length: types.LeInt(u16) align(1) = .from(@sizeOf(@This()) + data.len), num_descriptors: u8 = @intCast(objects.len), }{}); return .{ .data = header ++ data }; @@ -378,5 +376,5 @@ pub const HID = extern struct { /// Type of HID class report report_type: CsType = .Report, /// The total size of the Report descriptor - report_length: EndianInt(u16, .little) align(1), + report_length: types.LeInt(u16) align(1), }; diff --git a/core/src/core/usb/drivers/CDC.zig b/core/src/core/usb/drivers/CDC.zig index 3b82f790d..40059f34c 100644 --- a/core/src/core/usb/drivers/CDC.zig +++ b/core/src/core/usb/drivers/CDC.zig @@ -2,9 +2,6 @@ const std = @import("std"); const microzig = @import("../../../microzig.zig"); const assert = microzig.assert; -const mem = @import("../../mem.zig"); -const EndianInt = mem.EndianInt; - const usb = @import("../../usb.zig"); const log = std.log.scoped(.usb_cdc); @@ -45,7 +42,7 @@ pub const LineCoding = extern struct { _, }; - bit_rate: EndianInt(u32, .little), + bit_rate: usb.types.LeInt(u32), stop_bits: StopBits, parity: Parity, data_bits: u8, diff --git a/core/src/core/usb/types.zig b/core/src/core/usb/types.zig index 8ba7f36fd..d8e0bf151 100644 --- a/core/src/core/usb/types.zig +++ b/core/src/core/usb/types.zig @@ -1,5 +1,11 @@ const std = @import("std"); -const EndianInt = @import("../mem.zig").EndianInt; +const mem = @import("../mem.zig"); + +/// Little endian integer, unaffected by host endianness. +/// Commonly used in USB descriptors +pub fn LeInt(T: type) type { + return mem.EndianInt(T, .little); +} pub const ClassSubclassProtocol = extern struct { /// Class of device, giving a broad functional area. @@ -402,12 +408,12 @@ pub const SetupPacket = packed struct(u64) { /// conflict. request: u8, /// A simple argument of up to 16 bits, specific to the request. - value: EndianInt(u16, .little), - index: EndianInt(u16, .little), + value: LeInt(u16), + index: LeInt(u16), /// If data will be transferred after this request (in the direction given /// by `request_type`), this gives the number of bytes (OUT) or maximum /// number of bytes (IN). - length: EndianInt(u16, .little), + length: LeInt(u16), pub fn format(self: SetupPacket, writer: *std.Io.Writer) !void { try writer.print("request_type={} request={} value={} index={} length={}", .{ From fe0d81a6cf5cec214bcc740e0f653762dc1494d7 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Tue, 10 Nov 2026 20:01:47 +0100 Subject: [PATCH 04/28] usb.Config -> usb.Options; usb.Config.Configuration -> usb.Configuration --- core/src/core/usb.zig | 113 ++++++++++---------- examples/nordic/nrf5x/src/usb_cdc.zig | 11 +- examples/nordic/nrf5x/src/usb_hid.zig | 11 +- examples/raspberrypi/rp2xxx/src/usb_cdc.zig | 11 +- examples/raspberrypi/rp2xxx/src/usb_hid.zig | 11 +- examples/wch/ch32v/src/usb_cdc.zig | 11 +- port/raspberrypi/rp2xxx/src/hal/usb.zig | 4 +- 7 files changed, 84 insertions(+), 88 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index d534e24e0..625224038 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -146,43 +146,12 @@ pub fn DriverHandlers(Driver: type) type { return @Struct(.auto, null, field_names, &@splat(EndpointHandler(Driver)), &@splat(.{})); } -pub const Config = struct { +pub const Options = struct { pub const IdStringPair = struct { id: u16, str: []const u8, }; - pub const Configuration = struct { - name: []const u8 = "", - attributes: descriptor.Configuration.Attributes, - max_current_ma: u9, - Drivers: type, - - /// Generate A struct with a field for each field in Drivers, where the type is the third - /// arg of the Drivers' Descriptor's 'create' method. - pub fn Args(self: @This()) type { - const info = @typeInfo(self.Drivers).@"struct"; - const count = info.field_names.len; - var field_names: [count][:0]const u8 = undefined; - var field_types: [count]type = undefined; - for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { - // Collect field names - field_names[i] = field_name; - // Collect the type info for the Descriptor.create function parameter - const param_types = @typeInfo(@TypeOf(field_type.Descriptor.create)).@"fn".param_types; - // Ensure it takes 3 parameters - assert(param_types.len == 3); - // The first must be a DescriptorAllocator - assert(param_types[0] == *DescriptorAllocator); - // The second is usb.types.PacketLength - assert(param_types[1] == types.PacketLength); - // And save the type of the third - field_types[i] = param_types[2].?; - } - return @Struct(.auto, null, &field_names, &field_types, &@splat(.{})); - } - }; - /// Usb specification version. bcd_usb: types.Version, /// Class, subclass and protocol of this device. @@ -199,18 +168,40 @@ pub const Config = struct { serial: []const u8, /// Largest packet length the hardware supports. Must be a power of 2 and at least 8. max_supported_packet_size: types.PacketLength, - /// Currently only a single configuration is supported. - configurations: []const Configuration, /// Only use either IN or OUT on each endpoint. Useful for debugging. /// Realistically, it should only be turned off if you are exhausting /// the 15 endpoint limit. unique_endpoints: bool = true, +}; - pub fn DriverArgs(self: @This()) type { - var field_types: [self.configurations.len]type = undefined; - for (self.configurations, &field_types) |cfg, *dst| - dst.* = cfg.Args(); - return @Tuple(&field_types); +pub const Configuration = struct { + name: []const u8 = "", + attributes: descriptor.Configuration.Attributes, + max_current_ma: u9, + Drivers: type, + + /// Generate A struct with a field for each field in Drivers, where the type is the third + /// arg of the Drivers' Descriptor's 'create' method. + pub fn Args(self: @This()) type { + const info = @typeInfo(self.Drivers).@"struct"; + const count = info.field_names.len; + var field_names: [count][:0]const u8 = undefined; + var field_types: [count]type = undefined; + for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { + // Collect field names + field_names[i] = field_name; + // Collect the type info for the Descriptor.create function parameter + const param_types = @typeInfo(@TypeOf(field_type.Descriptor.create)).@"fn".param_types; + // Ensure it takes 3 parameters + assert(param_types.len == 3); + // The first must be a DescriptorAllocator + assert(param_types[0] == *DescriptorAllocator); + // The second is usb.types.PacketLength + assert(param_types[1] == types.PacketLength); + // And save the type of the third + field_types[i] = param_types[2].?; + } + return @Struct(.auto, null, &field_names, &field_types, &@splat(.{})); } }; @@ -229,13 +220,23 @@ pub fn validate_controller(T: type) void { /// /// Responds to host requests and dispatches to the appropriate drivers. /// When this type is build (at comptime), it builds descriptor and handler tables based on the -/// provided config. -pub fn DeviceController(config: Config, driver_args: config.DriverArgs()) type { - std.debug.assert(config.configurations.len == 1); +/// provided options. +pub fn DeviceController( + options: Options, + configurations: []const Configuration, + driver_args: blk: { + var field_types: [configurations.len]type = undefined; + for (configurations, &field_types) |cfg, *dst| + dst.* = cfg.Args(); + break :blk @Tuple(&field_types); + }, +) type { + // Currently only a single configuration is supported. + std.debug.assert(configurations.len == 1); return struct { // We only support one configuration - const config0 = config.configurations[0]; + const config0 = configurations[0]; const driver_info = @typeInfo(config0.Drivers).@"struct"; const DriverEnum = std.meta.FieldEnum(config0.Drivers); @@ -244,26 +245,26 @@ pub fn DeviceController(config: Config, driver_args: config.DriverArgs()) type { /// * table of handlers for endpoints /// * table of handlers for interfaces const descriptor_parse_result = blk: { - const max_psize = config.max_supported_packet_size; + const max_psize = options.max_supported_packet_size; assert(max_psize >= 8); assert(std.math.isPowerOfTwo(max_psize)); - var alloc: DescriptorAllocator = .init(config.unique_endpoints); - const manufacturer_s = alloc.string(config.vendor.str); - const product_s = alloc.string(config.product.str); - const serial_s = alloc.string(config.serial); + var alloc: DescriptorAllocator = .init(options.unique_endpoints); + const manufacturer_s = alloc.string(options.vendor.str); + const product_s = alloc.string(options.product.str); + const serial_s = alloc.string(options.serial); const desc_device: descriptor.Device = .{ - .bcd_usb = config.bcd_usb, - .device_triple = config.device_triple, - .max_packet_size0 = @min(config.max_supported_packet_size, 64), - .vendor = .from(config.vendor.id), - .product = .from(config.product.id), - .bcd_device = config.bcd_device, + .bcd_usb = options.bcd_usb, + .device_triple = options.device_triple, + .max_packet_size0 = @min(options.max_supported_packet_size, 64), + .vendor = .from(options.vendor.id), + .product = .from(options.product.id), + .bcd_device = options.bcd_device, .manufacturer_s = manufacturer_s, .product_s = product_s, .serial_s = serial_s, - .num_configurations = config.configurations.len, + .num_configurations = configurations.len, }; const configuration_s = alloc.string(config0.name); @@ -384,7 +385,7 @@ pub fn DeviceController(config: Config, driver_args: config.DriverArgs()) type { }, drv: DriverConfig = .{}, }{}, - .string_descriptors = const_alloc.string_descriptors(config.language), + .string_descriptors = const_alloc.string_descriptors(options.language), .handlers_itf = itf_handlers, .handlers_ep = struct { in: ep_handlers_types[idx_in] = const_ep_handlers[idx_in], diff --git a/examples/nordic/nrf5x/src/usb_cdc.zig b/examples/nordic/nrf5x/src/usb_cdc.zig index 0a5cbc99e..7308e34c3 100644 --- a/examples/nordic/nrf5x/src/usb_cdc.zig +++ b/examples/nordic/nrf5x/src/usb_cdc.zig @@ -40,12 +40,11 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = USBD.max_supported_packet_size, - .configurations = &.{.{ - .attributes = .{ .self_powered = false }, - .max_current_ma = 50, - .Drivers = struct { serial: USB_Serial }, - }}, -}, .{.{ +}, &.{.{ + .attributes = .{ .self_powered = false }, + .max_current_ma = 50, + .Drivers = struct { serial: USB_Serial }, +}}, .{.{ .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, }}) = .init; diff --git a/examples/nordic/nrf5x/src/usb_hid.zig b/examples/nordic/nrf5x/src/usb_hid.zig index 717850901..20f631d57 100644 --- a/examples/nordic/nrf5x/src/usb_hid.zig +++ b/examples/nordic/nrf5x/src/usb_hid.zig @@ -135,12 +135,11 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = USBD.max_supported_packet_size, - .configurations = &.{.{ - .attributes = .{ .self_powered = false }, - .max_current_ma = 50, - .Drivers = struct { keyboard: Keyboard }, - }}, -}, .{.{ +}, &.{.{ + .attributes = .{ .self_powered = false }, + .max_current_ma = 50, + .Drivers = struct { keyboard: Keyboard }, +}}, .{.{ .keyboard = .{ .itf_string = "Boot Keyboard", .poll_interval = 1 }, }}) = .init; diff --git a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig index edb307f0b..401f7debb 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig @@ -22,12 +22,11 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = USB_Device.max_supported_packet_size, - .configurations = &.{.{ - .attributes = .{ .self_powered = false }, - .max_current_ma = 50, - .Drivers = struct { serial: USB_Serial, reset: rp2xxx.usb.ResetDriver(null, 0) }, - }}, -}, .{.{ +}, &.{.{ + .attributes = .{ .self_powered = false }, + .max_current_ma = 50, + .Drivers = struct { serial: USB_Serial, reset: rp2xxx.usb.ResetDriver(null, 0) }, +}}, .{.{ .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, .reset = "", }}) = .init; diff --git a/examples/raspberrypi/rp2xxx/src/usb_hid.zig b/examples/raspberrypi/rp2xxx/src/usb_hid.zig index 90bc4d18e..fe4dfada6 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_hid.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_hid.zig @@ -128,12 +128,11 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = USB_Device.max_supported_packet_size, - .configurations = &.{.{ - .attributes = .{ .self_powered = false }, - .max_current_ma = 50, - .Drivers = struct { keyboard: Keyboard, reset: rp2xxx.usb.ResetDriver(null, 0) }, - }}, -}, .{.{ +}, &.{.{ + .attributes = .{ .self_powered = false }, + .max_current_ma = 50, + .Drivers = struct { keyboard: Keyboard, reset: rp2xxx.usb.ResetDriver(null, 0) }, +}}, .{.{ .keyboard = .{ .itf_string = "Boot Keyboard", .poll_interval = 1 }, .reset = "", }}) = .init; diff --git a/examples/wch/ch32v/src/usb_cdc.zig b/examples/wch/ch32v/src/usb_cdc.zig index 0854fdef2..0a1ad4e63 100644 --- a/examples/wch/ch32v/src/usb_cdc.zig +++ b/examples/wch/ch32v/src/usb_cdc.zig @@ -31,12 +31,11 @@ const USB_Controller = usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = hal.usb.max_packet_size, - .configurations = &.{.{ - .attributes = .{ .self_powered = false }, - .max_current_ma = 50, - .Drivers = struct { serial: USB_Serial }, - }}, -}, .{.{ +}, &.{.{ + .attributes = .{ .self_powered = false }, + .max_current_ma = 50, + .Drivers = struct { serial: USB_Serial }, +}}, .{.{ .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, }}); diff --git a/port/raspberrypi/rp2xxx/src/hal/usb.zig b/port/raspberrypi/rp2xxx/src/hal/usb.zig index 8098e1c47..63e090a93 100644 --- a/port/raspberrypi/rp2xxx/src/hal/usb.zig +++ b/port/raspberrypi/rp2xxx/src/hal/usb.zig @@ -86,8 +86,8 @@ pub fn Polled(config: Config) type { return struct { pub const max_supported_packet_size = 64; pub const max_supported_bcd_usb: usb.types.Version = .v1_10; - pub const default_vendor_id: usb.Config.IdStringPair = .{ .id = 0x2E8A, .str = "Raspberry Pi" }; - pub const default_product_id: usb.Config.IdStringPair = switch (chip) { + pub const default_vendor_id: usb.Options.IdStringPair = .{ .id = 0x2E8A, .str = "Raspberry Pi" }; + pub const default_product_id: usb.Options.IdStringPair = switch (chip) { .RP2040 => .{ .id = 0x000A, .str = "Pico test device" }, .RP2350 => .{ .id = 0x000F, .str = "Pico 2 test device" }, }; From 8a9997637d0c344cd9cebd3eee8622ba537c3059 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Tue, 10 Nov 2026 20:13:26 +0100 Subject: [PATCH 05/28] hid.zig -> HID.zig --- core/src/core/usb.zig | 2 +- core/src/core/usb/drivers/{hid.zig => HID.zig} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename core/src/core/usb/drivers/{hid.zig => HID.zig} (100%) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index 625224038..63a024153 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -6,7 +6,7 @@ pub const descriptor = @import("usb/descriptor.zig"); pub const drivers = struct { pub const CDC = @import("usb/drivers/CDC.zig"); pub const EchoExample = @import("usb/drivers/EchoExample.zig"); - pub const hid = @import("usb/drivers/hid.zig"); + pub const hid = @import("usb/drivers/HID.zig"); }; pub const types = @import("usb/types.zig"); diff --git a/core/src/core/usb/drivers/hid.zig b/core/src/core/usb/drivers/HID.zig similarity index 100% rename from core/src/core/usb/drivers/hid.zig rename to core/src/core/usb/drivers/HID.zig From 213c5251c6aaaa60fd06bf675e2cab944263da4f Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Tue, 10 Nov 2026 23:02:21 +0100 Subject: [PATCH 06/28] Move some usb.DeviceController functionality into usb.Configuration --- core/src/core/usb.zig | 210 ++++++++++++-------- examples/nordic/nrf5x/src/usb_cdc.zig | 5 +- examples/nordic/nrf5x/src/usb_hid.zig | 5 +- examples/raspberrypi/rp2xxx/src/usb_cdc.zig | 5 +- examples/raspberrypi/rp2xxx/src/usb_hid.zig | 5 +- examples/wch/ch32v/src/usb_cdc.zig | 5 +- 6 files changed, 134 insertions(+), 101 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index 63a024153..1b59d4418 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -175,33 +175,62 @@ pub const Options = struct { }; pub const Configuration = struct { - name: []const u8 = "", + const Input = struct { + name: []const u8 = "", + attributes: descriptor.Configuration.Attributes, + max_current_ma: u9, + }; + + str_id: u8, attributes: descriptor.Configuration.Attributes, max_current_ma: u9, - Drivers: type, - - /// Generate A struct with a field for each field in Drivers, where the type is the third - /// arg of the Drivers' Descriptor's 'create' method. - pub fn Args(self: @This()) type { - const info = @typeInfo(self.Drivers).@"struct"; - const count = info.field_names.len; - var field_names: [count][:0]const u8 = undefined; - var field_types: [count]type = undefined; - for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { - // Collect field names - field_names[i] = field_name; - // Collect the type info for the Descriptor.create function parameter - const param_types = @typeInfo(@TypeOf(field_type.Descriptor.create)).@"fn".param_types; - // Ensure it takes 3 parameters - assert(param_types.len == 3); - // The first must be a DescriptorAllocator - assert(param_types[0] == *DescriptorAllocator); - // The second is usb.types.PacketLength - assert(param_types[1] == types.PacketLength); - // And save the type of the third - field_types[i] = param_types[2].?; + RuntimeData: type, + + pub fn create( + alloc: *DescriptorAllocator, + input: Input, + RuntimeData: type, + ) @This() { + return .{ + .str_id = alloc.string(input.name), + .attributes = input.attributes, + .max_current_ma = input.max_current_ma, + .RuntimeData = RuntimeData, + }; + } + + pub fn init(comptime self: @This(), device_itf: *DeviceInterface, driver_data: *self.RuntimeData, driver_alloc: anytype, comptime config_descriptor: anytype) void { + inline for (@typeInfo(self.RuntimeData).@"struct".field_names) |driver_field_name| { + const cfg = @field(config_descriptor.drv, driver_field_name); + const desc_info = @typeInfo(@TypeOf(cfg)).@"struct"; + + // Open OUT endpoint first so that the driver can call ep_listen in init + inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { + const desc = &@field(cfg, field_name); + if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .out) + device_itf.ep_open(desc); + } + + const drv = &@field(driver_data, driver_field_name); + // Don't pass empty slices around + if (@hasField(@TypeOf(driver_alloc.*), driver_field_name)) + drv.init(&cfg, device_itf, &@field(driver_alloc, driver_field_name)) + else + drv.init(&cfg, device_itf); + + // Open IN endpoint last so that callbacks can happen + inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { + const desc = &@field(cfg, field_name); + if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .in) + device_itf.ep_open(desc); + } } - return @Struct(.auto, null, &field_names, &field_types, &@splat(.{})); + } + + pub fn deinit(comptime self: @This(), device_itf: *DeviceInterface, driver_data: *self.RuntimeData) void { + _ = device_itf; + _ = driver_data; + // deinitialize drivers } }; @@ -223,28 +252,48 @@ pub fn validate_controller(T: type) void { /// provided options. pub fn DeviceController( options: Options, - configurations: []const Configuration, + configurations: []const struct { Configuration.Input, type }, driver_args: blk: { - var field_types: [configurations.len]type = undefined; - for (configurations, &field_types) |cfg, *dst| - dst.* = cfg.Args(); - break :blk @Tuple(&field_types); + var field_types_outer: [configurations.len]type = undefined; + for (configurations, &field_types_outer) |cfg, *dst| { + const info = @typeInfo(cfg[1]).@"struct"; + const count = info.field_names.len; + var field_names: [count][:0]const u8 = undefined; + var field_types: [count]type = undefined; + for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { + // Collect field names + field_names[i] = field_name; + // Collect the type info for the Descriptor.create function parameter + const param_types = @typeInfo(@TypeOf(field_type.Descriptor.create)).@"fn".param_types; + // Ensure it takes 3 parameters + assert(param_types.len == 3); + // The first must be a DescriptorAllocator + assert(param_types[0] == *DescriptorAllocator); + // The second is usb.types.PacketLength + assert(param_types[1] == types.PacketLength); + // And save the type of the third + field_types[i] = param_types[2].?; + } + dst.* = @Struct(.auto, null, &field_names, &field_types, &@splat(.{})); + } + break :blk @Tuple(&field_types_outer); }, ) type { // Currently only a single configuration is supported. std.debug.assert(configurations.len == 1); return struct { - // We only support one configuration - const config0 = configurations[0]; - const driver_info = @typeInfo(config0.Drivers).@"struct"; - const DriverEnum = std.meta.FieldEnum(config0.Drivers); + const RuntimeData = configurations[0][1]; /// This parses the drivers' descriptors and creates: /// * the configuration descriptor (currently only one configuration is supported) /// * table of handlers for endpoints /// * table of handlers for interfaces const descriptor_parse_result = blk: { + const config0 = configurations[0][0]; + const driver_info = @typeInfo(RuntimeData).@"struct"; + const DriverEnum = std.meta.FieldEnum(RuntimeData); + const max_psize = options.max_supported_packet_size; assert(max_psize >= 8); assert(std.math.isPowerOfTwo(max_psize)); @@ -266,9 +315,9 @@ pub fn DeviceController( .serial_s = serial_s, .num_configurations = configurations.len, }; - const configuration_s = alloc.string(config0.name); - var size = @sizeOf(descriptor.Configuration); + const processed_config0 = Configuration.create(&alloc, configurations[0][0], configurations[0][1]); + var field_names: [driver_info.field_names.len][:0]const u8 = undefined; var field_types: [driver_info.field_names.len]type = undefined; var field_attrs: [driver_info.field_names.len]std.builtin.Type.Struct.FieldAttributes = undefined; @@ -298,7 +347,6 @@ pub fn DeviceController( } assert(@alignOf(Descriptors) == 1); - size += @sizeOf(Descriptors); // Collect handler types, names, and drivers, to later be bound to the appropriate // endpoints @@ -370,28 +418,43 @@ pub fn DeviceController( const const_ep_handlers = ep_handlers; const DriverConfig = @Struct(.@"extern", null, &field_names, &field_types, &field_attrs); + const ConfigDescriptor = extern struct { + first: descriptor.Configuration = .{ + .total_length = .from(@sizeOf(descriptor.Configuration) + @sizeOf(DriverConfig)), + .num_interfaces = const_alloc.next_itf_num, + .configuration_value = 1, + .configuration_s = processed_config0.str_id, + .attributes = config0.attributes, + .max_current = .from_ma(config0.max_current_ma), + }, + drv: DriverConfig = .{}, + }; + + std.testing.expectEqual( + (ConfigDescriptor{}).first.total_length.native(), + @sizeOf(ConfigDescriptor), + ) catch unreachable; + const idx_in = @backingInt(types.Dir.in); const idx_out = @backingInt(types.Dir.out); break :blk .{ .device_descriptor = desc_device, - .config_descriptor = extern struct { - first: descriptor.Configuration = .{ - .total_length = .from(size), - .num_interfaces = const_alloc.next_itf_num, - .configuration_value = 1, - .configuration_s = configuration_s, - .attributes = config0.attributes, - .max_current = .from_ma(config0.max_current_ma), - }, - drv: DriverConfig = .{}, - }{}, + .config_descriptor = ConfigDescriptor{}, .string_descriptors = const_alloc.string_descriptors(options.language), .handlers_itf = itf_handlers, .handlers_ep = struct { in: ep_handlers_types[idx_in] = const_ep_handlers[idx_in], out: ep_handlers_types[idx_out] = const_ep_handlers[idx_out], }{}, - .drivers_ep = ep_handler_drivers, + .drivers_ep = blk2: { + var ret: [2][16]?[]const u8 = undefined; + for (&ret, ep_handler_drivers) |*dstv, srcv| { + for (dstv, srcv) |*dst, src_opt| { + dst.* = if (src_opt) |src| field_names[src] else null; + } + } + break :blk2 ret; + }, .DriverAlloc = @Struct( .auto, null, @@ -399,6 +462,7 @@ pub fn DeviceController( driver_alloc_types[0..driver_alloc_attrs.len], driver_alloc_attrs[0..driver_alloc_attrs.len], ), + .processed_configurations = .{processed_config0}, }; }; @@ -411,6 +475,7 @@ pub fn DeviceController( .drv = descriptor_parse_result.drivers_ep, }; const DriverAlloc = descriptor_parse_result.DriverAlloc; + const processed_configurations = descriptor_parse_result.processed_configurations; /// If not zero, change the device address at the next opportunity. /// Necessary because when the host sets the device address, @@ -421,7 +486,7 @@ pub fn DeviceController( /// Ep0 data waiting to be sent tx_slice: ?[]const u8, /// Driver state - driver_data: ?config0.Drivers, + driver_data: ?RuntimeData, /// driver_alloc: DriverAlloc, @@ -436,7 +501,7 @@ pub fn DeviceController( /// Returns a pointer to the drivers /// or null in case host has not yet configured the device. - pub fn drivers(self: *@This()) ?*config0.Drivers { + pub fn drivers(self: *@This()) ?*RuntimeData { return if (self.driver_data) |*ret| ret else null; } @@ -495,7 +560,7 @@ pub fn DeviceController( log.warn("Unhandled packet on ep0 Out", .{}); if (comptime driver_opt) |driver| { - handler(&@field(self.driver_data.?, driver_info.field_names[driver]), ep.num); + handler(&@field(self.driver_data.?, driver), ep.num); } } @@ -587,43 +652,16 @@ pub fn DeviceController( fn process_set_config(self: *@This(), device_itf: *DeviceInterface, cfg_num: u16) void { if (cfg_num == self.cfg_num) return; - if (self.driver_data) |data_old| { - _ = data_old; - // deinitialize drivers - } + if (self.driver_data) |*data_old| + processed_configurations[0].deinit(device_itf, data_old); self.cfg_num = cfg_num; - if (cfg_num == 0) { - self.driver_data = null; - return; - } - - // We support just one config for now so ignore config index - self.driver_data = @as(config0.Drivers, undefined); - inline for (driver_info.field_names) |driver_field_name| { - const cfg = @field(config_descriptor.drv, driver_field_name); - const desc_info = @typeInfo(@TypeOf(cfg)).@"struct"; - - // Open OUT endpoint first so that the driver can call ep_listen in init - inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { - const desc = &@field(cfg, field_name); - if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .out) - device_itf.ep_open(desc); - } - - const drv = &@field(self.driver_data.?, driver_field_name); - // Don't pass empty slices around - if (@hasField(@TypeOf(self.driver_alloc), driver_field_name)) - drv.init(&cfg, device_itf, &@field(self.driver_alloc, driver_field_name)) - else - drv.init(&cfg, device_itf); - - // Open IN endpoint last so that callbacks can happen - inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { - const desc = &@field(cfg, field_name); - if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .in) - device_itf.ep_open(desc); - } + if (cfg_num == 0) + self.driver_data = null + else { + // We support just one config for now so ignore config index + self.driver_data = @as(RuntimeData, undefined); + processed_configurations[0].init(device_itf, &self.driver_data.?, &self.driver_alloc, config_descriptor); } } }; diff --git a/examples/nordic/nrf5x/src/usb_cdc.zig b/examples/nordic/nrf5x/src/usb_cdc.zig index 7308e34c3..de859b1cb 100644 --- a/examples/nordic/nrf5x/src/usb_cdc.zig +++ b/examples/nordic/nrf5x/src/usb_cdc.zig @@ -41,9 +41,8 @@ var usb_controller: usb.DeviceController(.{ .serial = "someserial", .max_supported_packet_size = USBD.max_supported_packet_size, }, &.{.{ - .attributes = .{ .self_powered = false }, - .max_current_ma = 50, - .Drivers = struct { serial: USB_Serial }, + .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, + struct { serial: USB_Serial }, }}, .{.{ .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, }}) = .init; diff --git a/examples/nordic/nrf5x/src/usb_hid.zig b/examples/nordic/nrf5x/src/usb_hid.zig index 20f631d57..ad3a03a58 100644 --- a/examples/nordic/nrf5x/src/usb_hid.zig +++ b/examples/nordic/nrf5x/src/usb_hid.zig @@ -136,9 +136,8 @@ var usb_controller: usb.DeviceController(.{ .serial = "someserial", .max_supported_packet_size = USBD.max_supported_packet_size, }, &.{.{ - .attributes = .{ .self_powered = false }, - .max_current_ma = 50, - .Drivers = struct { keyboard: Keyboard }, + .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, + struct { keyboard: Keyboard }, }}, .{.{ .keyboard = .{ .itf_string = "Boot Keyboard", .poll_interval = 1 }, }}) = .init; diff --git a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig index 401f7debb..787820b23 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig @@ -23,9 +23,8 @@ var usb_controller: usb.DeviceController(.{ .serial = "someserial", .max_supported_packet_size = USB_Device.max_supported_packet_size, }, &.{.{ - .attributes = .{ .self_powered = false }, - .max_current_ma = 50, - .Drivers = struct { serial: USB_Serial, reset: rp2xxx.usb.ResetDriver(null, 0) }, + .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, + struct { serial: USB_Serial, reset: rp2xxx.usb.ResetDriver(null, 0) }, }}, .{.{ .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, .reset = "", diff --git a/examples/raspberrypi/rp2xxx/src/usb_hid.zig b/examples/raspberrypi/rp2xxx/src/usb_hid.zig index fe4dfada6..0a822c0e9 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_hid.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_hid.zig @@ -129,9 +129,8 @@ var usb_controller: usb.DeviceController(.{ .serial = "someserial", .max_supported_packet_size = USB_Device.max_supported_packet_size, }, &.{.{ - .attributes = .{ .self_powered = false }, - .max_current_ma = 50, - .Drivers = struct { keyboard: Keyboard, reset: rp2xxx.usb.ResetDriver(null, 0) }, + .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, + struct { keyboard: Keyboard, reset: rp2xxx.usb.ResetDriver(null, 0) }, }}, .{.{ .keyboard = .{ .itf_string = "Boot Keyboard", .poll_interval = 1 }, .reset = "", diff --git a/examples/wch/ch32v/src/usb_cdc.zig b/examples/wch/ch32v/src/usb_cdc.zig index 0a1ad4e63..254db3479 100644 --- a/examples/wch/ch32v/src/usb_cdc.zig +++ b/examples/wch/ch32v/src/usb_cdc.zig @@ -32,9 +32,8 @@ const USB_Controller = usb.DeviceController(.{ .serial = "someserial", .max_supported_packet_size = hal.usb.max_packet_size, }, &.{.{ - .attributes = .{ .self_powered = false }, - .max_current_ma = 50, - .Drivers = struct { serial: USB_Serial }, + .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, + struct { serial: USB_Serial }, }}, .{.{ .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, }}); From 8bf2d557ba62eee657a88a2aa430b1d7ad3689a5 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Wed, 11 Nov 2026 00:19:12 +0100 Subject: [PATCH 07/28] Move configuration descriptor generation into usb.Configuration --- core/src/core/usb.zig | 358 ++++++++++---------- examples/nordic/nrf5x/src/usb_cdc.zig | 9 +- examples/nordic/nrf5x/src/usb_hid.zig | 9 +- examples/raspberrypi/rp2xxx/src/usb_cdc.zig | 11 +- examples/raspberrypi/rp2xxx/src/usb_hid.zig | 11 +- examples/wch/ch32v/src/usb_cdc.zig | 9 +- 6 files changed, 207 insertions(+), 200 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index 1b59d4418..8c003412c 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -174,149 +174,51 @@ pub const Options = struct { unique_endpoints: bool = true, }; -pub const Configuration = struct { - const Input = struct { - name: []const u8 = "", - attributes: descriptor.Configuration.Attributes, - max_current_ma: u9, - }; - - str_id: u8, +pub const ConfigurationOptions = struct { + name: []const u8 = "", attributes: descriptor.Configuration.Attributes, max_current_ma: u9, - RuntimeData: type, - - pub fn create( - alloc: *DescriptorAllocator, - input: Input, - RuntimeData: type, - ) @This() { - return .{ - .str_id = alloc.string(input.name), - .attributes = input.attributes, - .max_current_ma = input.max_current_ma, - .RuntimeData = RuntimeData, - }; - } - - pub fn init(comptime self: @This(), device_itf: *DeviceInterface, driver_data: *self.RuntimeData, driver_alloc: anytype, comptime config_descriptor: anytype) void { - inline for (@typeInfo(self.RuntimeData).@"struct".field_names) |driver_field_name| { - const cfg = @field(config_descriptor.drv, driver_field_name); - const desc_info = @typeInfo(@TypeOf(cfg)).@"struct"; - - // Open OUT endpoint first so that the driver can call ep_listen in init - inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { - const desc = &@field(cfg, field_name); - if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .out) - device_itf.ep_open(desc); - } - - const drv = &@field(driver_data, driver_field_name); - // Don't pass empty slices around - if (@hasField(@TypeOf(driver_alloc.*), driver_field_name)) - drv.init(&cfg, device_itf, &@field(driver_alloc, driver_field_name)) - else - drv.init(&cfg, device_itf); - - // Open IN endpoint last so that callbacks can happen - inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { - const desc = &@field(cfg, field_name); - if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .in) - device_itf.ep_open(desc); - } - } - } - - pub fn deinit(comptime self: @This(), device_itf: *DeviceInterface, driver_data: *self.RuntimeData) void { - _ = device_itf; - _ = driver_data; - // deinitialize drivers - } }; -pub fn validate_controller(T: type) void { - comptime { - const info = @typeInfo(T); - if (info != .pointer or info.pointer.attrs.@"const" or info.pointer.size != .one) - @compileError("Expected a mutable pointer to the usb controller, got: " ++ @typeName(T)); - const Controller = info.pointer.child; - _ = Controller; - // More checks - } -} - -/// USB device controller -/// -/// Responds to host requests and dispatches to the appropriate drivers. -/// When this type is build (at comptime), it builds descriptor and handler tables based on the -/// provided options. -pub fn DeviceController( - options: Options, - configurations: []const struct { Configuration.Input, type }, +pub fn Configuration( + options: ConfigurationOptions, + Drivers: type, driver_args: blk: { - var field_types_outer: [configurations.len]type = undefined; - for (configurations, &field_types_outer) |cfg, *dst| { - const info = @typeInfo(cfg[1]).@"struct"; - const count = info.field_names.len; - var field_names: [count][:0]const u8 = undefined; - var field_types: [count]type = undefined; - for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { - // Collect field names - field_names[i] = field_name; - // Collect the type info for the Descriptor.create function parameter - const param_types = @typeInfo(@TypeOf(field_type.Descriptor.create)).@"fn".param_types; - // Ensure it takes 3 parameters - assert(param_types.len == 3); - // The first must be a DescriptorAllocator - assert(param_types[0] == *DescriptorAllocator); - // The second is usb.types.PacketLength - assert(param_types[1] == types.PacketLength); - // And save the type of the third - field_types[i] = param_types[2].?; - } - dst.* = @Struct(.auto, null, &field_names, &field_types, &@splat(.{})); + const info = @typeInfo(Drivers).@"struct"; + const count = info.field_names.len; + var field_names: [count][:0]const u8 = undefined; + var field_types: [count]type = undefined; + for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { + // Collect field names + field_names[i] = field_name; + // Collect the type info for the Descriptor.create function parameter + const param_types = @typeInfo(@TypeOf(field_type.Descriptor.create)).@"fn".param_types; + // Ensure it takes 3 parameters + assert(param_types.len == 3); + // The first must be a DescriptorAllocator + assert(param_types[0] == *DescriptorAllocator); + // The second is usb.types.PacketLength + assert(param_types[1] == types.PacketLength); + // And save the type of the third + field_types[i] = param_types[2].?; } - break :blk @Tuple(&field_types_outer); + break :blk @Struct(.auto, null, &field_names, &field_types, &@splat(.{})); }, ) type { - // Currently only a single configuration is supported. - std.debug.assert(configurations.len == 1); - return struct { - const RuntimeData = configurations[0][1]; - - /// This parses the drivers' descriptors and creates: - /// * the configuration descriptor (currently only one configuration is supported) - /// * table of handlers for endpoints - /// * table of handlers for interfaces - const descriptor_parse_result = blk: { - const config0 = configurations[0][0]; + const RuntimeData = Drivers; + const DriverEnum = std.meta.FieldEnum(RuntimeData); + + Descriptor: type, + DriverAlloc: type, + drivers_ep: [2][16]?DriverEnum, + HandlersEp: type, + handlers_itf: []const DriverEnum, + + pub fn create(unique_endpoints: bool, max_psize: types.PacketLength, strings: []const []const u8) struct { @This(), []const []const u8 } { + var alloc = DescriptorAllocator.init(unique_endpoints); + alloc.strings = strings; const driver_info = @typeInfo(RuntimeData).@"struct"; - const DriverEnum = std.meta.FieldEnum(RuntimeData); - - const max_psize = options.max_supported_packet_size; - assert(max_psize >= 8); - assert(std.math.isPowerOfTwo(max_psize)); - - var alloc: DescriptorAllocator = .init(options.unique_endpoints); - const manufacturer_s = alloc.string(options.vendor.str); - const product_s = alloc.string(options.product.str); - const serial_s = alloc.string(options.serial); - - const desc_device: descriptor.Device = .{ - .bcd_usb = options.bcd_usb, - .device_triple = options.device_triple, - .max_packet_size0 = @min(options.max_supported_packet_size, 64), - .vendor = .from(options.vendor.id), - .product = .from(options.product.id), - .bcd_device = options.bcd_device, - .manufacturer_s = manufacturer_s, - .product_s = product_s, - .serial_s = serial_s, - .num_configurations = configurations.len, - }; - - const processed_config0 = Configuration.create(&alloc, configurations[0][0], configurations[0][1]); var field_names: [driver_info.field_names.len][:0]const u8 = undefined; var field_types: [driver_info.field_names.len]type = undefined; @@ -324,7 +226,7 @@ pub fn DeviceController( var ep_handler_types: [2][16]type = @splat(@splat(void)); var ep_handler_names: [2][16][:0]const u8 = undefined; var ep_handler_drivers: [2][16]?usize = @splat(@splat(null)); - var itf_handlers: []const DriverEnum = &.{}; + var handlers_itf: []const DriverEnum = &.{}; var driver_alloc_names: []const [:0]const u8 = &.{}; var driver_alloc_types: []const type = &.{}; var driver_alloc_attrs: []const std.builtin.Type.Struct.FieldAttributes = &.{}; @@ -333,7 +235,7 @@ pub fn DeviceController( // Get descriptor type for the current driver const Descriptors = driver_field_type.Descriptor; // Call the create method on the descriptor, which wraps it with the allow stuff. - const result = Descriptors.create(&alloc, max_psize, @field(driver_args[0], driver_field_name)); + const result = Descriptors.create(&alloc, max_psize, @field(driver_args, driver_field_name)); // Get the descriptor instance from the result. const descriptors = result.descriptor; @@ -368,10 +270,10 @@ pub fn DeviceController( @typeName(T), ), }; - if (itf_start != itf_handlers.len) + if (itf_start != handlers_itf.len) @compileError("interface numbering mismatch"); - itf_handlers = itf_handlers ++ @as([itf_count]DriverEnum, @splat(@field(DriverEnum, driver_field_name))); + handlers_itf = handlers_itf ++ @as([itf_count]DriverEnum, @splat(@field(DriverEnum, driver_field_name))); } switch (field_type) { @@ -412,71 +314,171 @@ pub fn DeviceController( } } + const configuration_s = alloc.string(options.name); + // alloc is invalidated after this point. It will cause a compile // error if mutated. const const_alloc = alloc.to_const(); const const_ep_handlers = ep_handlers; const DriverConfig = @Struct(.@"extern", null, &field_names, &field_types, &field_attrs); - const ConfigDescriptor = extern struct { + const Descriptor = extern struct { first: descriptor.Configuration = .{ .total_length = .from(@sizeOf(descriptor.Configuration) + @sizeOf(DriverConfig)), .num_interfaces = const_alloc.next_itf_num, .configuration_value = 1, - .configuration_s = processed_config0.str_id, - .attributes = config0.attributes, - .max_current = .from_ma(config0.max_current_ma), + .configuration_s = configuration_s, + .attributes = options.attributes, + .max_current = .from_ma(options.max_current_ma), }, drv: DriverConfig = .{}, }; std.testing.expectEqual( - (ConfigDescriptor{}).first.total_length.native(), - @sizeOf(ConfigDescriptor), + (Descriptor{}).first.total_length.native(), + @sizeOf(Descriptor), ) catch unreachable; const idx_in = @backingInt(types.Dir.in); const idx_out = @backingInt(types.Dir.out); + return .{ + .{ + .Descriptor = Descriptor, + .DriverAlloc = @Struct( + .auto, + null, + driver_alloc_names, + driver_alloc_types[0..driver_alloc_attrs.len], + driver_alloc_attrs[0..driver_alloc_attrs.len], + ), + .drivers_ep = blk: { + var ret: @FieldType(@This(), "drivers_ep") = undefined; + for (&ret, ep_handler_drivers) |*dstv, srcv| { + for (dstv, srcv) |*dst, src_opt| { + dst.* = if (src_opt) |src| @field(DriverEnum, field_names[src]) else null; + } + } + break :blk ret; + }, + .HandlersEp = struct { + in: ep_handlers_types[idx_in] = const_ep_handlers[idx_in], + out: ep_handlers_types[idx_out] = const_ep_handlers[idx_out], + }, + .handlers_itf = handlers_itf, + }, + const_alloc.strings, + }; + } + + pub fn init(device_itf: *DeviceInterface, driver_data: *RuntimeData, driver_alloc: anytype, comptime config_descriptor: anytype) void { + inline for (@typeInfo(RuntimeData).@"struct".field_names) |driver_field_name| { + const cfg = @field(config_descriptor.drv, driver_field_name); + const desc_info = @typeInfo(@TypeOf(cfg)).@"struct"; + + // Open OUT endpoint first so that the driver can call ep_listen in init + inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { + const desc = &@field(cfg, field_name); + if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .out) + device_itf.ep_open(desc); + } + + const drv = &@field(driver_data, driver_field_name); + // Don't pass empty slices around + if (@hasField(@TypeOf(driver_alloc.*), driver_field_name)) + drv.init(&cfg, device_itf, &@field(driver_alloc, driver_field_name)) + else + drv.init(&cfg, device_itf); + + // Open IN endpoint last so that callbacks can happen + inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { + const desc = &@field(cfg, field_name); + if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .in) + device_itf.ep_open(desc); + } + } + } + + pub fn deinit(device_itf: *DeviceInterface, driver_data: *RuntimeData) void { + _ = device_itf; + _ = driver_data; + // deinitialize drivers + } + }; +} + +pub fn validate_controller(T: type) void { + comptime { + const info = @typeInfo(T); + if (info != .pointer or info.pointer.attrs.@"const" or info.pointer.size != .one) + @compileError("Expected a mutable pointer to the usb controller, got: " ++ @typeName(T)); + const Controller = info.pointer.child; + _ = Controller; + // More checks + } +} + +/// USB device controller +/// +/// Responds to host requests and dispatches to the appropriate drivers. +/// When this type is build (at comptime), it builds descriptor and handler tables based on the +/// provided options. +pub fn DeviceController(options: Options, configurations: []const type) type { + // Currently only a single configuration is supported. + std.debug.assert(configurations.len == 1); + + return struct { + const RuntimeData = configurations[0].RuntimeData; + + /// This parses the drivers' descriptors and creates: + /// * the configuration descriptor (currently only one configuration is supported) + /// * table of handlers for endpoints + /// * table of handlers for interfaces + const descriptor_parse_result = blk: { + const max_psize = options.max_supported_packet_size; + assert(max_psize >= 8); + assert(std.math.isPowerOfTwo(max_psize)); + + var alloc: DescriptorAllocator = .init(options.unique_endpoints); + const manufacturer_s = alloc.string(options.vendor.str); + const product_s = alloc.string(options.product.str); + const serial_s = alloc.string(options.serial); + + const desc_device: descriptor.Device = .{ + .bcd_usb = options.bcd_usb, + .device_triple = options.device_triple, + .max_packet_size0 = @min(options.max_supported_packet_size, 64), + .vendor = .from(options.vendor.id), + .product = .from(options.product.id), + .bcd_device = options.bcd_device, + .manufacturer_s = manufacturer_s, + .product_s = product_s, + .serial_s = serial_s, + .num_configurations = configurations.len, + }; + + const config0, alloc.strings = configurations[0].create(options.unique_endpoints, max_psize, alloc.strings); + + // alloc is invalidated after this point. It will cause a compile + // error if mutated. + const const_alloc = alloc.to_const(); + break :blk .{ .device_descriptor = desc_device, - .config_descriptor = ConfigDescriptor{}, .string_descriptors = const_alloc.string_descriptors(options.language), - .handlers_itf = itf_handlers, - .handlers_ep = struct { - in: ep_handlers_types[idx_in] = const_ep_handlers[idx_in], - out: ep_handlers_types[idx_out] = const_ep_handlers[idx_out], - }{}, - .drivers_ep = blk2: { - var ret: [2][16]?[]const u8 = undefined; - for (&ret, ep_handler_drivers) |*dstv, srcv| { - for (dstv, srcv) |*dst, src_opt| { - dst.* = if (src_opt) |src| field_names[src] else null; - } - } - break :blk2 ret; - }, - .DriverAlloc = @Struct( - .auto, - null, - driver_alloc_names, - driver_alloc_types[0..driver_alloc_attrs.len], - driver_alloc_attrs[0..driver_alloc_attrs.len], - ), - .processed_configurations = .{processed_config0}, + .processed_configurations = .{config0}, }; }; - const config_descriptor = descriptor_parse_result.config_descriptor; const device_descriptor = descriptor_parse_result.device_descriptor; const string_descriptors = descriptor_parse_result.string_descriptors; - const handlers_itf = descriptor_parse_result.handlers_itf; - const handlers_ep = .{ - .han = descriptor_parse_result.handlers_ep, - .drv = descriptor_parse_result.drivers_ep, - }; - const DriverAlloc = descriptor_parse_result.DriverAlloc; const processed_configurations = descriptor_parse_result.processed_configurations; + const config_descriptor = processed_configurations[0].Descriptor{}; + const handlers_itf = processed_configurations[0].handlers_itf; + const handlers_ep = processed_configurations[0].HandlersEp{}; + const drivers_ep = processed_configurations[0].drivers_ep; + const DriverAlloc = processed_configurations[0].DriverAlloc; + /// If not zero, change the device address at the next opportunity. /// Necessary because when the host sets the device address, /// the acknowledgement step must use the _old_ address. @@ -530,8 +532,8 @@ pub fn DeviceController( pub fn on_buffer(self: *@This(), device_itf: *DeviceInterface, comptime ep: types.Endpoint) void { log.debug("on_buffer {t} {t}", .{ ep.num, ep.dir }); - const driver_opt = comptime handlers_ep.drv[@backingInt(ep.dir)][@backingInt(ep.num)]; - const handler = comptime @field(handlers_ep.han, @tagName(ep.dir))[@backingInt(ep.num)]; + const driver_opt = comptime drivers_ep[@backingInt(ep.dir)][@backingInt(ep.num)]; + const handler = comptime @field(handlers_ep, @tagName(ep.dir))[@backingInt(ep.num)]; if (comptime ep == types.Endpoint.in(.ep0)) { // We use this opportunity to finish the delayed @@ -560,7 +562,7 @@ pub fn DeviceController( log.warn("Unhandled packet on ep0 Out", .{}); if (comptime driver_opt) |driver| { - handler(&@field(self.driver_data.?, driver), ep.num); + handler(&@field(self.driver_data.?, @tagName(driver)), ep.num); } } @@ -653,7 +655,7 @@ pub fn DeviceController( if (cfg_num == self.cfg_num) return; if (self.driver_data) |*data_old| - processed_configurations[0].deinit(device_itf, data_old); + @TypeOf(processed_configurations[0]).deinit(device_itf, data_old); self.cfg_num = cfg_num; if (cfg_num == 0) @@ -661,7 +663,7 @@ pub fn DeviceController( else { // We support just one config for now so ignore config index self.driver_data = @as(RuntimeData, undefined); - processed_configurations[0].init(device_itf, &self.driver_data.?, &self.driver_alloc, config_descriptor); + @TypeOf(processed_configurations[0]).init(device_itf, &self.driver_data.?, &self.driver_alloc, config_descriptor); } } }; diff --git a/examples/nordic/nrf5x/src/usb_cdc.zig b/examples/nordic/nrf5x/src/usb_cdc.zig index de859b1cb..c38e9f9ab 100644 --- a/examples/nordic/nrf5x/src/usb_cdc.zig +++ b/examples/nordic/nrf5x/src/usb_cdc.zig @@ -40,12 +40,13 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = USBD.max_supported_packet_size, -}, &.{.{ +}, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, struct { serial: USB_Serial }, -}}, .{.{ - .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, -}}) = .init; + .{ + .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, + }, +)}) = .init; pub fn main() !void { board.init(); diff --git a/examples/nordic/nrf5x/src/usb_hid.zig b/examples/nordic/nrf5x/src/usb_hid.zig index ad3a03a58..7df6cfdc6 100644 --- a/examples/nordic/nrf5x/src/usb_hid.zig +++ b/examples/nordic/nrf5x/src/usb_hid.zig @@ -135,12 +135,13 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = USBD.max_supported_packet_size, -}, &.{.{ +}, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, struct { keyboard: Keyboard }, -}}, .{.{ - .keyboard = .{ .itf_string = "Boot Keyboard", .poll_interval = 1 }, -}}) = .init; + .{ + .keyboard = .{ .itf_string = "Boot Keyboard", .poll_interval = 1 }, + }, +)}) = .init; pub fn main() !void { board.init(); diff --git a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig index 787820b23..660d39944 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig @@ -22,13 +22,14 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = USB_Device.max_supported_packet_size, -}, &.{.{ +}, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, struct { serial: USB_Serial, reset: rp2xxx.usb.ResetDriver(null, 0) }, -}}, .{.{ - .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, - .reset = "", -}}) = .init; + .{ + .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, + .reset = "", + }, +)}) = .init; pub const std_options = microzig.std_options(.{ .log_level = .debug, diff --git a/examples/raspberrypi/rp2xxx/src/usb_hid.zig b/examples/raspberrypi/rp2xxx/src/usb_hid.zig index 0a822c0e9..2617735e6 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_hid.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_hid.zig @@ -128,13 +128,14 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = USB_Device.max_supported_packet_size, -}, &.{.{ +}, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, struct { keyboard: Keyboard, reset: rp2xxx.usb.ResetDriver(null, 0) }, -}}, .{.{ - .keyboard = .{ .itf_string = "Boot Keyboard", .poll_interval = 1 }, - .reset = "", -}}) = .init; + .{ + .keyboard = .{ .itf_string = "Boot Keyboard", .poll_interval = 1 }, + .reset = "", + }, +)}) = .init; pub fn panic(message: []const u8, _: ?*std.builtin.StackTrace, _: ?usize) noreturn { std.log.err("panic: {s}", .{message}); diff --git a/examples/wch/ch32v/src/usb_cdc.zig b/examples/wch/ch32v/src/usb_cdc.zig index 254db3479..19a4d5708 100644 --- a/examples/wch/ch32v/src/usb_cdc.zig +++ b/examples/wch/ch32v/src/usb_cdc.zig @@ -31,12 +31,13 @@ const USB_Controller = usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = hal.usb.max_packet_size, -}, &.{.{ +}, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, struct { serial: USB_Serial }, -}}, .{.{ - .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, -}}); + .{ + .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, + }, +)}); pub var usb_dev: hal.usb.Polled(board.usb_setup, .{}) = undefined; From 80e0fed54a4477c651717c1d55a603639782f225 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Wed, 11 Nov 2026 01:14:28 +0100 Subject: [PATCH 08/28] Cleanup usb a little --- core/src/core/usb.zig | 137 +++++++++++++++++++++--------------------- 1 file changed, 70 insertions(+), 67 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index 8c003412c..992c38584 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -13,19 +13,20 @@ pub const types = @import("usb/types.zig"); pub const ack: []const u8 = ""; pub const nak: ?[]const u8 = null; -// What does this do? It lets you iterate through interfaces and endpoints? +/// Helper struct for endpoint allocation for drivers. +/// Also deduplicates static strings. pub const DescriptorAllocator = struct { next_ep_num: [2]u8, next_itf_num: u8, unique_endpoints: bool, strings: []const []const u8, - pub fn init(unique_endpoints: bool) @This() { + pub fn init(unique_endpoints: bool, strings: []const []const u8) @This() { return .{ .next_ep_num = @splat(1), .next_itf_num = 0, .unique_endpoints = unique_endpoints, - .strings = &.{}, + .strings = strings, }; } @@ -44,21 +45,7 @@ pub const DescriptorAllocator = struct { } pub fn string(self: *@This(), str: []const u8) u8 { - if (str.len == 0) return 0; - // deduplicate - for (self.strings, 1..) |s, i| { - if (std.mem.eql(u8, s, str)) - return i; - } - - self.strings = self.strings ++ .{str}; - return @intCast(self.strings.len); - } - - pub fn string_descriptors(self: @This(), lang: descriptor.String.Language) []const descriptor.String { - var ret: []const descriptor.String = &.{.from_lang(lang)}; - for (self.strings) |s| - ret = ret ++ [1]descriptor.String{.from_str(s)}; + self.strings, const ret = dedup_string(self.strings, str); return ret; } @@ -168,16 +155,16 @@ pub const Options = struct { serial: []const u8, /// Largest packet length the hardware supports. Must be a power of 2 and at least 8. max_supported_packet_size: types.PacketLength, - /// Only use either IN or OUT on each endpoint. Useful for debugging. - /// Realistically, it should only be turned off if you are exhausting - /// the 15 endpoint limit. - unique_endpoints: bool = true, }; pub const ConfigurationOptions = struct { - name: []const u8 = "", attributes: descriptor.Configuration.Attributes, max_current_ma: u9, + name: []const u8 = "", + /// Only use either IN or OUT on each endpoint. Useful for debugging. + /// Realistically, it should only be turned off if you are exhausting + /// the 15 endpoint limit. + unique_endpoints: bool = true, }; pub fn Configuration( @@ -206,18 +193,20 @@ pub fn Configuration( }, ) type { return struct { - const RuntimeData = Drivers; - const DriverEnum = std.meta.FieldEnum(RuntimeData); + const DriverName = []const u8; Descriptor: type, DriverAlloc: type, - drivers_ep: [2][16]?DriverEnum, + drivers_ep: [2][16]?DriverName, HandlersEp: type, - handlers_itf: []const DriverEnum, + handlers_itf: []const DriverName, + RuntimeData: type, + + pub fn create(max_psize: types.PacketLength, strings: []const []const u8) struct { @This(), []const []const u8 } { + const RuntimeData = Drivers; - pub fn create(unique_endpoints: bool, max_psize: types.PacketLength, strings: []const []const u8) struct { @This(), []const []const u8 } { - var alloc = DescriptorAllocator.init(unique_endpoints); - alloc.strings = strings; + var alloc = DescriptorAllocator.init(options.unique_endpoints, strings); + const configuration_s = alloc.string(options.name); const driver_info = @typeInfo(RuntimeData).@"struct"; var field_names: [driver_info.field_names.len][:0]const u8 = undefined; @@ -226,7 +215,7 @@ pub fn Configuration( var ep_handler_types: [2][16]type = @splat(@splat(void)); var ep_handler_names: [2][16][:0]const u8 = undefined; var ep_handler_drivers: [2][16]?usize = @splat(@splat(null)); - var handlers_itf: []const DriverEnum = &.{}; + var handlers_itf: []const DriverName = &.{}; var driver_alloc_names: []const [:0]const u8 = &.{}; var driver_alloc_types: []const type = &.{}; var driver_alloc_attrs: []const std.builtin.Type.Struct.FieldAttributes = &.{}; @@ -273,7 +262,7 @@ pub fn Configuration( if (itf_start != handlers_itf.len) @compileError("interface numbering mismatch"); - handlers_itf = handlers_itf ++ @as([itf_count]DriverEnum, @splat(@field(DriverEnum, driver_field_name))); + handlers_itf = handlers_itf ++ @as([itf_count]DriverName, @splat(driver_field_name)); } switch (field_type) { @@ -314,10 +303,7 @@ pub fn Configuration( } } - const configuration_s = alloc.string(options.name); - - // alloc is invalidated after this point. It will cause a compile - // error if mutated. + // alloc is invalidated after this point. It will cause a compile error if accessed. const const_alloc = alloc.to_const(); const const_ep_handlers = ep_handlers; @@ -355,7 +341,7 @@ pub fn Configuration( var ret: @FieldType(@This(), "drivers_ep") = undefined; for (&ret, ep_handler_drivers) |*dstv, srcv| { for (dstv, srcv) |*dst, src_opt| { - dst.* = if (src_opt) |src| @field(DriverEnum, field_names[src]) else null; + dst.* = if (src_opt) |src| field_names[src] else null; } } break :blk ret; @@ -365,13 +351,14 @@ pub fn Configuration( out: ep_handlers_types[idx_out] = const_ep_handlers[idx_out], }, .handlers_itf = handlers_itf, + .RuntimeData = RuntimeData, }, const_alloc.strings, }; } - pub fn init(device_itf: *DeviceInterface, driver_data: *RuntimeData, driver_alloc: anytype, comptime config_descriptor: anytype) void { - inline for (@typeInfo(RuntimeData).@"struct".field_names) |driver_field_name| { + pub fn init(comptime self: @This(), device_itf: *DeviceInterface, driver_data: *self.RuntimeData, driver_alloc: anytype, comptime config_descriptor: anytype) void { + inline for (@typeInfo(self.RuntimeData).@"struct".field_names) |driver_field_name| { const cfg = @field(config_descriptor.drv, driver_field_name); const desc_info = @typeInfo(@TypeOf(cfg)).@"struct"; @@ -398,7 +385,7 @@ pub fn Configuration( } } - pub fn deinit(device_itf: *DeviceInterface, driver_data: *RuntimeData) void { + pub fn deinit(comptime self: @This(), device_itf: *DeviceInterface, driver_data: *self.RuntimeData) void { _ = device_itf; _ = driver_data; // deinitialize drivers @@ -422,15 +409,13 @@ pub fn validate_controller(T: type) void { /// Responds to host requests and dispatches to the appropriate drivers. /// When this type is build (at comptime), it builds descriptor and handler tables based on the /// provided options. -pub fn DeviceController(options: Options, configurations: []const type) type { +pub fn DeviceController(options: Options, Configurations: []const type) type { // Currently only a single configuration is supported. - std.debug.assert(configurations.len == 1); + std.debug.assert(Configurations.len == 1); return struct { - const RuntimeData = configurations[0].RuntimeData; - /// This parses the drivers' descriptors and creates: - /// * the configuration descriptor (currently only one configuration is supported) + /// * the configuration descriptor /// * table of handlers for endpoints /// * table of handlers for interfaces const descriptor_parse_result = blk: { @@ -438,10 +423,10 @@ pub fn DeviceController(options: Options, configurations: []const type) type { assert(max_psize >= 8); assert(std.math.isPowerOfTwo(max_psize)); - var alloc: DescriptorAllocator = .init(options.unique_endpoints); - const manufacturer_s = alloc.string(options.vendor.str); - const product_s = alloc.string(options.product.str); - const serial_s = alloc.string(options.serial); + var strings: []const []const u8 = &.{}; + strings, const manufacturer_s = dedup_string(strings, options.vendor.str); + strings, const product_s = dedup_string(strings, options.product.str); + strings, const serial_s = dedup_string(strings, options.serial); const desc_device: descriptor.Device = .{ .bcd_usb = options.bcd_usb, @@ -453,31 +438,34 @@ pub fn DeviceController(options: Options, configurations: []const type) type { .manufacturer_s = manufacturer_s, .product_s = product_s, .serial_s = serial_s, - .num_configurations = configurations.len, + .num_configurations = Configurations.len, }; - const config0, alloc.strings = configurations[0].create(options.unique_endpoints, max_psize, alloc.strings); + var configs: @Tuple(Configurations) = undefined; + for (0..Configurations.len) |i| + configs[i], strings = Configurations[i].create(max_psize, strings); - // alloc is invalidated after this point. It will cause a compile - // error if mutated. - const const_alloc = alloc.to_const(); + var desc_string: []const descriptor.String = &.{.from_lang(options.language)}; + for (strings) |s| + desc_string = desc_string ++ [1]descriptor.String{.from_str(s)}; break :blk .{ .device_descriptor = desc_device, - .string_descriptors = const_alloc.string_descriptors(options.language), - .processed_configurations = .{config0}, + .string_descriptors = desc_string, + .configurations = configs, }; }; const device_descriptor = descriptor_parse_result.device_descriptor; const string_descriptors = descriptor_parse_result.string_descriptors; - const processed_configurations = descriptor_parse_result.processed_configurations; + const configurations = descriptor_parse_result.configurations; - const config_descriptor = processed_configurations[0].Descriptor{}; - const handlers_itf = processed_configurations[0].handlers_itf; - const handlers_ep = processed_configurations[0].HandlersEp{}; - const drivers_ep = processed_configurations[0].drivers_ep; - const DriverAlloc = processed_configurations[0].DriverAlloc; + const config_descriptor = configurations[0].Descriptor{}; + const handlers_itf = configurations[0].handlers_itf; + const handlers_ep = configurations[0].HandlersEp{}; + const drivers_ep = configurations[0].drivers_ep; + const DriverAlloc = configurations[0].DriverAlloc; + const RuntimeData = configurations[0].RuntimeData; /// If not zero, change the device address at the next opportunity. /// Necessary because when the host sets the device address, @@ -489,7 +477,7 @@ pub fn DeviceController(options: Options, configurations: []const type) type { tx_slice: ?[]const u8, /// Driver state driver_data: ?RuntimeData, - /// + /// Additional driver allocations (size is comptime-known) driver_alloc: DriverAlloc, /// Initial values @@ -562,7 +550,7 @@ pub fn DeviceController(options: Options, configurations: []const type) type { log.warn("Unhandled packet on ep0 Out", .{}); if (comptime driver_opt) |driver| { - handler(&@field(self.driver_data.?, @tagName(driver)), ep.num); + handler(&@field(self.driver_data.?, driver), ep.num); } } @@ -620,7 +608,7 @@ pub fn DeviceController(options: Options, configurations: []const type) type { switch (itf_num) { inline else => |itf| if (comptime itf < handlers_itf.len) { const drv = handlers_itf[itf]; - return @field(self.driver_data.?, @tagName(drv)).class_request(setup); + return @field(self.driver_data.?, drv).class_request(setup); } else { log.warn("Interface index ({}) out of range ({})", .{ itf_num, handlers_itf.len }); return nak; @@ -655,7 +643,7 @@ pub fn DeviceController(options: Options, configurations: []const type) type { if (cfg_num == self.cfg_num) return; if (self.driver_data) |*data_old| - @TypeOf(processed_configurations[0]).deinit(device_itf, data_old); + configurations[0].deinit(device_itf, data_old); self.cfg_num = cfg_num; if (cfg_num == 0) @@ -663,8 +651,23 @@ pub fn DeviceController(options: Options, configurations: []const type) type { else { // We support just one config for now so ignore config index self.driver_data = @as(RuntimeData, undefined); - @TypeOf(processed_configurations[0]).init(device_itf, &self.driver_data.?, &self.driver_alloc, config_descriptor); + configurations[0].init(device_itf, &self.driver_data.?, &self.driver_alloc, config_descriptor); } } }; } + +fn dedup_string( + comptime strings: []const []const u8, + comptime new: []const u8, +) struct { []const []const u8, u8 } { + if (new.len == 0) + return .{ strings, 0 }; + // deduplicate + for (strings, 1..) |s, i| { + if (std.mem.eql(u8, s, new)) + return .{ strings, i }; + } + const new_strings = strings ++ .{new}; + return .{ new_strings, @intCast(new_strings.len) }; +} From 11900906293f7b5adce8de95a54cea42dce63f71 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Wed, 11 Nov 2026 02:22:58 +0100 Subject: [PATCH 09/28] Separate runtime in USB drivers --- core/src/core/usb.zig | 34 +-- core/src/core/usb/drivers/CDC.zig | 244 ++++++++++---------- core/src/core/usb/drivers/EchoExample.zig | 134 +++++------ core/src/core/usb/drivers/HID.zig | 113 ++++----- examples/nordic/nrf5x/src/usb_cdc.zig | 4 +- examples/nordic/nrf5x/src/usb_hid.zig | 90 ++++---- examples/raspberrypi/rp2xxx/src/usb_cdc.zig | 4 +- examples/raspberrypi/rp2xxx/src/usb_hid.zig | 93 ++++---- examples/wch/ch32v/src/usb_cdc.zig | 4 +- port/nordic/nrf5x/src/hal/usbd.zig | 4 +- port/raspberrypi/rp2xxx/src/hal/usb.zig | 54 ++--- 11 files changed, 404 insertions(+), 374 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index 992c38584..0c87013a4 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -6,7 +6,7 @@ pub const descriptor = @import("usb/descriptor.zig"); pub const drivers = struct { pub const CDC = @import("usb/drivers/CDC.zig"); pub const EchoExample = @import("usb/drivers/EchoExample.zig"); - pub const hid = @import("usb/drivers/HID.zig"); + pub const HID_Interrupt = @import("usb/drivers/HID.zig"); }; pub const types = @import("usb/types.zig"); @@ -121,7 +121,7 @@ pub fn EndpointHandler(Driver: type) type { return fn (*Driver, types.Endpoint.Num) void; } -pub fn DriverHandlers(Driver: type) type { +pub fn DriverHandlers(Driver: type, Runtime: type) type { var field_names: []const [:0]const u8 = &.{}; const info = @typeInfo(Driver.Descriptor).@"struct"; @@ -130,7 +130,7 @@ pub fn DriverHandlers(Driver: type) type { else => {}, }; - return @Struct(.auto, null, field_names, &@splat(EndpointHandler(Driver)), &@splat(.{})); + return @Struct(.auto, null, field_names, &@splat(EndpointHandler(Runtime)), &@splat(.{})); } pub const Options = struct { @@ -203,14 +203,13 @@ pub fn Configuration( RuntimeData: type, pub fn create(max_psize: types.PacketLength, strings: []const []const u8) struct { @This(), []const []const u8 } { - const RuntimeData = Drivers; - var alloc = DescriptorAllocator.init(options.unique_endpoints, strings); const configuration_s = alloc.string(options.name); - const driver_info = @typeInfo(RuntimeData).@"struct"; + const driver_info = @typeInfo(Drivers).@"struct"; var field_names: [driver_info.field_names.len][:0]const u8 = undefined; - var field_types: [driver_info.field_names.len]type = undefined; + var desc_field_types: [driver_info.field_names.len]type = undefined; + var runtime_field_types: [driver_info.field_names.len]type = undefined; var field_attrs: [driver_info.field_names.len]std.builtin.Type.Struct.FieldAttributes = undefined; var ep_handler_types: [2][16]type = @splat(@splat(void)); var ep_handler_names: [2][16][:0]const u8 = undefined; @@ -220,9 +219,14 @@ pub fn Configuration( var driver_alloc_types: []const type = &.{}; var driver_alloc_attrs: []const std.builtin.Type.Struct.FieldAttributes = &.{}; - for (driver_info.field_names, driver_info.field_types, 0..) |driver_field_name, driver_field_type, drv_id| { + for (driver_info.field_names, driver_info.field_types, 0..) |driver_field_name, DriverType, drv_id| { + runtime_field_types[drv_id] = if (@hasField(DriverType, "generic_runtime")) + DriverType.Runtime(@field(driver_args, driver_field_name).generic_runtime) + else + DriverType.Runtime; + // Get descriptor type for the current driver - const Descriptors = driver_field_type.Descriptor; + const Descriptors = DriverType.Descriptor; // Call the create method on the descriptor, which wraps it with the allow stuff. const result = Descriptors.create(&alloc, max_psize, @field(driver_args, driver_field_name)); // Get the descriptor instance from the result. @@ -254,7 +258,7 @@ pub fn Configuration( descriptor.Interface => .{ desc.interface_number, 1 }, else => |T| @compileError( "Expected first descriptor of driver " ++ - @typeName(driver_field_type) ++ + @typeName(DriverType) ++ " to be of type Interface or InterfaceAssociation descriptor, got: " ++ @typeName(T), ), @@ -277,7 +281,7 @@ pub fn Configuration( .{ ep_num, desc.endpoint.dir, ep_handler_drivers[ep_dir][ep_num], driver_field_name }, )); - ep_handler_types[ep_dir][ep_num] = EndpointHandler(driver_field_type); + ep_handler_types[ep_dir][ep_num] = EndpointHandler(runtime_field_types[drv_id]); ep_handler_drivers[ep_dir][ep_num] = drv_id; ep_handler_names[ep_dir][ep_num] = field_name; }, @@ -287,7 +291,7 @@ pub fn Configuration( } } field_names[drv_id] = driver_field_name; - field_types[drv_id] = Descriptors; + desc_field_types[drv_id] = Descriptors; field_attrs[drv_id] = .{ .default_value_ptr = &descriptors }; } @@ -299,7 +303,7 @@ pub fn Configuration( for (&ep_handler_types, &ep_handler_names, &ep_handler_drivers, 0..) |htypes, hnames, hdrivers, dir| { for (&htypes, &hnames, &hdrivers, 0..) |T, name, drv_id, ep| { if (T != void) - ep_handlers[dir][ep] = @field(driver_info.field_types[drv_id.?].handlers, name); + ep_handlers[dir][ep] = @field(runtime_field_types[drv_id.?].handlers, name); } } @@ -307,7 +311,7 @@ pub fn Configuration( const const_alloc = alloc.to_const(); const const_ep_handlers = ep_handlers; - const DriverConfig = @Struct(.@"extern", null, &field_names, &field_types, &field_attrs); + const DriverConfig = @Struct(.@"extern", null, &field_names, &desc_field_types, &field_attrs); const Descriptor = extern struct { first: descriptor.Configuration = .{ .total_length = .from(@sizeOf(descriptor.Configuration) + @sizeOf(DriverConfig)), @@ -351,7 +355,7 @@ pub fn Configuration( out: ep_handlers_types[idx_out] = const_ep_handlers[idx_out], }, .handlers_itf = handlers_itf, - .RuntimeData = RuntimeData, + .RuntimeData = @Struct(.auto, null, &field_names, &runtime_field_types, &@splat(.{})), }, const_alloc.strings, }; diff --git a/core/src/core/usb/drivers/CDC.zig b/core/src/core/usb/drivers/CDC.zig index 40059f34c..5c8cae8a7 100644 --- a/core/src/core/usb/drivers/CDC.zig +++ b/core/src/core/usb/drivers/CDC.zig @@ -55,6 +55,8 @@ pub const LineCoding = extern struct { }; }; +const CDC_Driver = @This(); + // This struct bundles all the descriptors CDC needs into one Configuration. pub const Descriptor = extern struct { const desc = usb.descriptor; @@ -148,133 +150,137 @@ pub const Descriptor = extern struct { } }; -// These field names are matched (at comptime) to the field names in the descriptor returned from -// `create` when binding the endpoints. -pub const handlers: usb.DriverHandlers(@This()) = .{ - .ep_notifi = on_notifi_ready, - .ep_out = on_rx, - .ep_in = on_tx_ready, -}; +pub const Runtime = struct { + device: *usb.DeviceInterface, + descriptor: *const Descriptor, + line_coding: LineCoding align(4), + notifi_ready: std.atomic.Value(bool), + + rx_data: []u8, + rx_seek: usb.types.PacketLength, + rx_end: usb.types.PacketLength, + rx_ready: std.atomic.Value(bool), + + tx_data: []u8, + tx_end: usb.types.PacketLength, + tx_ready: std.atomic.Value(bool), + + pub fn available(self: *@This()) usb.types.PacketLength { + return self.rx_end - self.rx_seek; + } + + pub fn read(self: *@This(), dst: []u8) usize { + const len = @min(dst.len, self.rx_end - self.rx_seek); + @memcpy(dst[0..len], self.rx_data[self.rx_seek..][0..len]); + self.rx_seek += len; -device: *usb.DeviceInterface, -descriptor: *const Descriptor, -line_coding: LineCoding align(4), -notifi_ready: std.atomic.Value(bool), - -rx_data: []u8, -rx_seek: usb.types.PacketLength, -rx_end: usb.types.PacketLength, -rx_ready: std.atomic.Value(bool), - -tx_data: []u8, -tx_end: usb.types.PacketLength, -tx_ready: std.atomic.Value(bool), - -pub fn available(self: *@This()) usb.types.PacketLength { - return self.rx_end - self.rx_seek; -} - -pub fn read(self: *@This(), dst: []u8) usize { - const len = @min(dst.len, self.rx_end - self.rx_seek); - @memcpy(dst[0..len], self.rx_data[self.rx_seek..][0..len]); - self.rx_seek += len; - - if (self.available() > 0) return len; - - // request more data - if (self.rx_ready.load(.seq_cst)) { - const ep_out = self.descriptor.ep_out.endpoint.num; - self.rx_ready.store(false, .seq_cst); - self.rx_end = self.device.ep_readv(ep_out, &.{self.rx_data}); - self.rx_seek = 0; - self.device.ep_listen(ep_out, @intCast(self.rx_data.len)); + if (self.available() > 0) return len; + + // request more data + if (self.rx_ready.load(.seq_cst)) { + const ep_out = self.descriptor.ep_out.endpoint.num; + self.rx_ready.store(false, .seq_cst); + self.rx_end = self.device.ep_readv(ep_out, &.{self.rx_data}); + self.rx_seek = 0; + self.device.ep_listen(ep_out, @intCast(self.rx_data.len)); + } + + return len; } - return len; -} + pub fn write(self: *@This(), data: []const u8) usize { + const len = @min(self.tx_data.len - self.tx_end, data.len); -pub fn write(self: *@This(), data: []const u8) usize { - const len = @min(self.tx_data.len - self.tx_end, data.len); + @memcpy(self.tx_data[self.tx_end..][0..len], data[0..len]); + self.tx_end += @intCast(len); - @memcpy(self.tx_data[self.tx_end..][0..len], data[0..len]); - self.tx_end += @intCast(len); + if (self.tx_end == self.tx_data.len) + _ = self.flush(); + + return len; + } - if (self.tx_end == self.tx_data.len) - _ = self.flush(); + /// Flushes tx buffer. Returns true if there is no more buffered data. + pub fn flush(self: *@This()) bool { + if (self.tx_end == 0) + return true; - return len; -} + if (!self.tx_ready.load(.seq_cst)) + return false; + self.tx_ready.store(false, .seq_cst); -/// Flushes tx buffer. Returns true if there is no more buffered data. -pub fn flush(self: *@This()) bool { - if (self.tx_end == 0) + assert(self.tx_end == self.device.ep_writev( + self.descriptor.ep_in.endpoint.num, + &.{self.tx_data[0..self.tx_end]}, + ), .{}); + self.tx_end = 0; return true; + } - if (!self.tx_ready.load(.seq_cst)) - return false; - self.tx_ready.store(false, .seq_cst); - - assert(self.tx_end == self.device.ep_writev( - self.descriptor.ep_in.endpoint.num, - &.{self.tx_data[0..self.tx_end]}, - ), .{}); - self.tx_end = 0; - return true; -} - -// Called when the host selects a configuration. -pub fn init(self: *@This(), desc: *const Descriptor, device: *usb.DeviceInterface, data: []u8) void { - const len_half = @divExact(data.len, 2); - assert(len_half == desc.ep_in.max_packet_size.native(), .{}); - assert(len_half == desc.ep_out.max_packet_size.native(), .{}); - self.* = .{ - .device = device, - .descriptor = desc, - .line_coding = .init, - .notifi_ready = .init(true), - - // `init` provides a data buffer, which we split in half for rx and tx data. - .rx_data = data[0..len_half], - .rx_seek = 0, - .rx_end = 0, - .rx_ready = .init(false), - - .tx_data = data[len_half..], - .tx_end = 0, - .tx_ready = .init(true), - }; - device.ep_listen(desc.ep_out.endpoint.num, @intCast(self.rx_data.len)); -} - -/// Handle class-specific SETUP requests where recipient=Interface -/// Called by DeviceController when the interface number matches this driver. -pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { - const mgmt_request: ManagementRequestType = @fromBackingInt(setup.request); - log.debug("cdc setup: {any} {} {}", .{ mgmt_request, setup.length.native(), setup.value.native() }); - - return switch (mgmt_request) { - .SetLineCoding => usb.ack, // we should handle data phase somehow to read sent line_coding - .GetLineCoding => std.mem.asBytes(&self.line_coding), - .SetControlLineState => usb.ack, - .SendBreak => usb.ack, - else => usb.nak, + // *** USB driver interface below *** + + // These field names are matched (at comptime) to the field names in the descriptor returned from + // `create` when binding the endpoints. + pub const handlers: usb.DriverHandlers(CDC_Driver, @This()) = .{ + .ep_notifi = on_notifi_ready, + .ep_out = on_rx, + .ep_in = on_tx_ready, }; -} - -pub fn on_rx(self: *@This(), ep_num: usb.types.Endpoint.Num) void { - if (self.rx_ready.load(.seq_cst)) - log.warn("{s}({t}) called before buffer was consumed", .{ "on_rx", ep_num }); - self.rx_ready.store(true, .seq_cst); -} - -pub fn on_tx_ready(self: *@This(), ep_num: usb.types.Endpoint.Num) void { - if (self.tx_ready.load(.seq_cst)) - log.warn("{s}({t}) called before buffer was consumed", .{ "on_tx_ready", ep_num }); - self.tx_ready.store(true, .seq_cst); -} - -pub fn on_notifi_ready(self: *@This(), ep_num: usb.types.Endpoint.Num) void { - if (self.notifi_ready.load(.seq_cst)) - log.warn("{s}({t}) called before buffer was consumed", .{ "on_notifi_ready", ep_num }); - self.notifi_ready.store(true, .seq_cst); -} + + // Called when the host selects a configuration. + pub fn init(self: *@This(), desc: *const Descriptor, device: *usb.DeviceInterface, data: []u8) void { + const len_half = @divExact(data.len, 2); + assert(len_half == desc.ep_in.max_packet_size.native(), .{}); + assert(len_half == desc.ep_out.max_packet_size.native(), .{}); + self.* = .{ + .device = device, + .descriptor = desc, + .line_coding = .init, + .notifi_ready = .init(true), + + // `init` provides a data buffer, which we split in half for rx and tx data. + .rx_data = data[0..len_half], + .rx_seek = 0, + .rx_end = 0, + .rx_ready = .init(false), + + .tx_data = data[len_half..], + .tx_end = 0, + .tx_ready = .init(true), + }; + device.ep_listen(desc.ep_out.endpoint.num, @intCast(self.rx_data.len)); + } + + /// Handle class-specific SETUP requests where recipient=Interface + /// Called by DeviceController when the interface number matches this driver. + pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { + const mgmt_request: ManagementRequestType = @fromBackingInt(setup.request); + log.debug("cdc setup: {any} {} {}", .{ mgmt_request, setup.length.native(), setup.value.native() }); + + return switch (mgmt_request) { + .SetLineCoding => usb.ack, // we should handle data phase somehow to read sent line_coding + .GetLineCoding => std.mem.asBytes(&self.line_coding), + .SetControlLineState => usb.ack, + .SendBreak => usb.ack, + else => usb.nak, + }; + } + + pub fn on_rx(self: *@This(), ep_num: usb.types.Endpoint.Num) void { + if (self.rx_ready.load(.seq_cst)) + log.warn("{s}({t}) called before buffer was consumed", .{ "on_rx", ep_num }); + self.rx_ready.store(true, .seq_cst); + } + + pub fn on_tx_ready(self: *@This(), ep_num: usb.types.Endpoint.Num) void { + if (self.tx_ready.load(.seq_cst)) + log.warn("{s}({t}) called before buffer was consumed", .{ "on_tx_ready", ep_num }); + self.tx_ready.store(true, .seq_cst); + } + + pub fn on_notifi_ready(self: *@This(), ep_num: usb.types.Endpoint.Num) void { + if (self.notifi_ready.load(.seq_cst)) + log.warn("{s}({t}) called before buffer was consumed", .{ "on_notifi_ready", ep_num }); + self.notifi_ready.store(true, .seq_cst); + } +}; diff --git a/core/src/core/usb/drivers/EchoExample.zig b/core/src/core/usb/drivers/EchoExample.zig index a4fd8b19f..79898aecf 100644 --- a/core/src/core/usb/drivers/EchoExample.zig +++ b/core/src/core/usb/drivers/EchoExample.zig @@ -4,6 +4,8 @@ const usb = @import("../../usb.zig"); const assert = std.debug.assert; const log = std.log.scoped(.usb_echo); +pub const EchoExampleDriver = @This(); + /// The descriptors need to have the same memory layout as the sent data. pub const Descriptor = extern struct { const desc = usb.descriptor; @@ -31,8 +33,8 @@ pub const Descriptor = extern struct { .interface_triple = .vendor_specific, .interface_s = alloc.string(itf_string), }, - .ep_out = .bulk(alloc.next_ep(.Out), max_supported_packet_size), - .ep_in = .bulk(alloc.next_ep(.In), max_supported_packet_size), + .ep_out = .bulk(alloc.next_ep(.out), max_supported_packet_size), + .ep_in = .bulk(alloc.next_ep(.in), max_supported_packet_size), }, // Buffers whose length is only known after creating the // descriptor can be allocated at this stage. @@ -41,73 +43,75 @@ pub const Descriptor = extern struct { } }; -/// This is a mapping from endpoint descriptor field names to handler function names. -/// 'in' and 'out' are from the perspective of the host, so, usb devices send data on 'in' endpoints -/// and receive on 'out' endpoints. -pub const handlers: usb.DriverHandlers(@This()) = .{ - .ep_in = on_tx_ready, - .ep_out = on_rx, -}; +pub const Runtime = struct { + /// This is a mapping from endpoint descriptor field names to handler function names. + /// 'in' and 'out' are from the perspective of the host, so, usb devices send data on 'in' endpoints + /// and receive on 'out' endpoints. + pub const handlers: usb.DriverHandlers(EchoExampleDriver, @This()) = .{ + .ep_in = on_tx_ready, + .ep_out = on_rx, + }; -device: *usb.DeviceInterface, -descriptor: *const Descriptor, -packet_buffer: []u8, -tx_ready: std.atomic.Value(bool), + device: *usb.DeviceInterface, + descriptor: *const Descriptor, + packet_buffer: []u8, + tx_ready: std.atomic.Value(bool), -/// This function is called when the host chooses a configuration that contains this driver. `self` -/// points to undefined memory. `data` is of the length specified in `Descriptor.create()`. -pub fn init(self: *@This(), desc: *const Descriptor, device: *usb.DeviceInterface, data: []u8) void { - assert(data.len == desc.ep_in.max_packet_size.native()); - self.* = .{ - .device = device, - .descriptor = desc, - .packet_buffer = data, - .tx_ready = .init(false), - }; - device.ep_listen( - desc.ep_out.endpoint.num, - @intCast(desc.ep_out.max_packet_size.native()), - ); -} + /// This function is called when the host chooses a configuration that contains this driver. `self` + /// points to undefined memory. `data` is of the length specified in `Descriptor.create()`. + pub fn init(self: *@This(), desc: *const Descriptor, device: *usb.DeviceInterface, data: []u8) void { + assert(data.len == desc.ep_in.max_packet_size.native()); + self.* = .{ + .device = device, + .descriptor = desc, + .packet_buffer = data, + .tx_ready = .init(false), + }; + device.ep_listen( + desc.ep_out.endpoint.num, + @intCast(desc.ep_out.max_packet_size.native()), + ); + } -/// Used for interface configuration through endpoint 0. -/// Data returned by this function is sent on endpoint 0. -pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { - _ = self; - log.debug("setup: {x}, {}, {}", .{ setup.request, setup.length.native(), setup.value.native() }); - return usb.ack; -} + /// Used for interface configuration through endpoint 0. + /// Data returned by this function is sent on endpoint 0. + pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { + _ = self; + log.debug("setup: {x}, {}, {}", .{ setup.request, setup.length.native(), setup.value.native() }); + return usb.ack; + } -/// Transmit handler callback. -/// Each endpoint (as defined in the descriptor) has its own handler. -/// Endpoint number is passed as an argument so that it does not need to be stored in the driver. -pub fn on_tx_ready(self: *@This(), ep_tx: usb.types.Endpoint.Num) void { - log.info("tx ready ({t})", .{ep_tx}); - // Mark transmission as available - self.tx_ready.store(true, .seq_cst); -} + /// Transmit handler callback. + /// Each endpoint (as defined in the descriptor) has its own handler. + /// Endpoint number is passed as an argument so that it does not need to be stored in the driver. + pub fn on_tx_ready(self: *@This(), ep_tx: usb.types.Endpoint.Num) void { + log.info("tx ready ({t})", .{ep_tx}); + // Mark transmission as available + self.tx_ready.store(true, .seq_cst); + } -/// Receive handler callback. -/// Endpoint number is passed as an argument so that it does not need to be stored in the driver. -pub fn on_rx(self: *@This(), ep_rx: usb.types.Endpoint.Num) void { - var buf: [64]u8 = undefined; - // Read incoming packet into a local buffer - const len_rx = self.device.ep_readv(ep_rx, &.{&buf}); - log.info("Received on {t}: {s}", .{ ep_rx, buf[0..len_rx] }); + /// Receive handler callback. + /// Endpoint number is passed as an argument so that it does not need to be stored in the driver. + pub fn on_rx(self: *@This(), ep_rx: usb.types.Endpoint.Num) void { + var buf: [64]u8 = undefined; + // Read incoming packet into a local buffer + const len_rx = self.device.ep_readv(ep_rx, &.{&buf}); + log.info("Received on {t}: {s}", .{ ep_rx, buf[0..len_rx] }); - // Check if we can transmit - if (self.tx_ready.load(.seq_cst)) { - // Mark transmission as not available - self.tx_ready.store(false, .seq_cst); - // Send received packet - log.info("Sending {} bytes", .{len_rx}); - const len_tx = self.device.ep_writev( - self.descriptor.ep_in.endpoint.num, - &.{buf[0..len_rx]}, - ); - if (len_tx != len_rx) - log.err("Only sent {} bytes", .{len_tx}); + // Check if we can transmit + if (self.tx_ready.load(.seq_cst)) { + // Mark transmission as not available + self.tx_ready.store(false, .seq_cst); + // Send received packet + log.info("Sending {} bytes", .{len_rx}); + const len_tx = self.device.ep_writev( + self.descriptor.ep_in.endpoint.num, + &.{buf[0..len_rx]}, + ); + if (len_tx != len_rx) + log.err("Only sent {} bytes", .{len_tx}); + } + // Listen for next packet + self.device.ep_listen(ep_rx, 64); } - // Listen for next packet - self.device.ep_listen(ep_rx, 64); -} +}; diff --git a/core/src/core/usb/drivers/HID.zig b/core/src/core/usb/drivers/HID.zig index e00af333d..559d8e87b 100644 --- a/core/src/core/usb/drivers/HID.zig +++ b/core/src/core/usb/drivers/HID.zig @@ -293,16 +293,65 @@ pub const ReportItem = union(enum) { const ClassCode = usb.types.ClassSubclassProtocol.ClassCode.HID; -pub const InterruptDriverOptions = struct { - subclass: ClassCode.Subclass(), - protocol: ClassCode.Protocol(), +pub const HID_InterruptDriver = @This(); + +subclass: ClassCode.Subclass(), +protocol: ClassCode.Protocol(), + +itf_string: []const u8 = "", +poll_interval: u8, +country_code: usb.descriptor.HID.CountryCode = .NotSupported, + +generic_runtime: struct { + report_descriptor: []const ?ReportItem, InReport: type, OutReport: type, - report_descriptor: []const ?ReportItem, +}, + +pub const Descriptor = extern struct { + const desc = usb.descriptor; + + interface: desc.Interface, + hid: desc.HID, + ep_out: desc.Endpoint, + ep_in: desc.Endpoint, + + pub fn create( + alloc: *usb.DescriptorAllocator, + max_supported_packet_size: usb.types.PacketLength, + options: HID_InterruptDriver, + ) usb.DescriptorCreateResult(@This()) { + assert(@sizeOf(options.generic_runtime.InReport) <= max_supported_packet_size); + assert(@sizeOf(options.generic_runtime.OutReport) <= max_supported_packet_size); + return .{ .descriptor = .{ + .interface = .{ + .interface_number = alloc.next_itf(), + .alternate_setting = 0, + .num_endpoints = 2, + .interface_triple = .from(.HID, options.subclass, options.protocol), + .interface_s = alloc.string(options.itf_string), + }, + .hid = .{ + .country_code = options.country_code, + .num_descriptors = 1, + .report_length = .from(options.generic_runtime.report_descriptor.len), + }, + .ep_out = .interrupt( + alloc.next_ep(.out), + @sizeOf(options.generic_runtime.OutReport), + options.poll_interval, + ), + .ep_in = .interrupt( + alloc.next_ep(.in), + @sizeOf(options.generic_runtime.InReport), + options.poll_interval, + ), + } }; + } }; /// HID Driver with an IN and OUT endpoint -pub fn InterruptDriver(options: InterruptDriverOptions) type { +pub fn Runtime(options: @FieldType(HID_InterruptDriver, "generic_runtime")) type { const log = std.log.scoped(.usb_hid_int_driver); return struct { @@ -321,65 +370,19 @@ pub fn InterruptDriver(options: InterruptDriverOptions) type { const OutReport = options.OutReport; const InReport = options.InReport; - pub const Descriptor = extern struct { - const desc = usb.descriptor; - - interface: desc.Interface, - hid: desc.HID, - ep_out: desc.Endpoint, - ep_in: desc.Endpoint, - - pub const Options = struct { - itf_string: []const u8 = "", - poll_interval: u8, - country_code: desc.HID.CountryCode = .NotSupported, - }; - - pub fn create( - alloc: *usb.DescriptorAllocator, - max_supported_packet_size: usb.types.PacketLength, - desc_options: Options, - ) usb.DescriptorCreateResult(@This()) { - assert(@sizeOf(InReport) <= max_supported_packet_size); - assert(@sizeOf(OutReport) <= max_supported_packet_size); - return .{ .descriptor = .{ - .interface = .{ - .interface_number = alloc.next_itf(), - .alternate_setting = 0, - .num_endpoints = 2, - .interface_triple = .from(.HID, options.subclass, options.protocol), - .interface_s = alloc.string(desc_options.itf_string), - }, - .hid = .{ - .country_code = desc_options.country_code, - .num_descriptors = 1, - .report_length = .from(report_descriptor.len), - }, - .ep_out = .interrupt( - alloc.next_ep(.out), - @sizeOf(OutReport), - desc_options.poll_interval, - ), - .ep_in = .interrupt( - alloc.next_ep(.in), - @sizeOf(InReport), - desc_options.poll_interval, - ), - } }; - } - }; + pub const Descriptor = HID_InterruptDriver.Descriptor; - pub const handlers: usb.DriverHandlers(@This()) = .{ + pub const handlers: usb.DriverHandlers(HID_InterruptDriver, @This()) = .{ .ep_in = on_tx_ready, .ep_out = on_rx, }; device: *usb.DeviceInterface, - descriptor: *const Descriptor, + descriptor: *const @This().Descriptor, tx_ready: std.atomic.Value(bool), rx_ready: std.atomic.Value(bool), - pub fn init(self: *@This(), desc: *const Descriptor, device: *usb.DeviceInterface) void { + pub fn init(self: *@This(), desc: *const @This().Descriptor, device: *usb.DeviceInterface) void { log.debug("init", .{}); self.* = .{ .device = device, diff --git a/examples/nordic/nrf5x/src/usb_cdc.zig b/examples/nordic/nrf5x/src/usb_cdc.zig index c38e9f9ab..f63030db9 100644 --- a/examples/nordic/nrf5x/src/usb_cdc.zig +++ b/examples/nordic/nrf5x/src/usb_cdc.zig @@ -96,7 +96,7 @@ var usb_tx_buff: [1024]u8 = undefined; /// Transfer data to host /// NOTE: After each USB chunk transfer, we have to call the USB task so that bus TX events can be /// handled -pub fn usb_cdc_write(serial: *USB_Serial, comptime fmt: []const u8, args: anytype) void { +pub fn usb_cdc_write(serial: *USB_Serial.Runtime, comptime fmt: []const u8, args: anytype) void { var tx = std.fmt.bufPrint(&usb_tx_buff, fmt, args) catch &.{}; while (tx.len > 0) { @@ -113,7 +113,7 @@ var usb_rx_buff: [1024]u8 = undefined; /// Receive data from host /// NOTE: Read code was not tested extensively. In case of issues, try to call USB task before every /// read operation -pub fn usb_cdc_read(serial: *USB_Serial) []const u8 { +pub fn usb_cdc_read(serial: *USB_Serial.Runtime) []const u8 { var rx_len: usize = 0; while (true) { diff --git a/examples/nordic/nrf5x/src/usb_hid.zig b/examples/nordic/nrf5x/src/usb_hid.zig index 7df6cfdc6..c1618a6bf 100644 --- a/examples/nordic/nrf5x/src/usb_hid.zig +++ b/examples/nordic/nrf5x/src/usb_hid.zig @@ -80,50 +80,54 @@ pub const KeyboardOutReport = packed struct(u8) { padding: u5 = 0, }; -const Keyboard = usb.drivers.hid.InterruptDriver(.{ +const hid_driver_options: usb.drivers.HID_Interrupt = .{ .subclass = .Boot, .protocol = .Boot, - .report_descriptor = &.{ - .{ .global_usage_page = .generic_desktop }, - .local_usage_enum(.{ .generic_desktop = .keyboard }), - .{ .main_collection = .Application }, - // Input: modifier key bitmap - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0xE0, 0xE7 }, - .count = 8, - .Child = bool, - .dir = .in, - .type = .dynamic, - } }, - // Reserved 8 bits - .{ .data_static = .{ .in, u8 } }, - // Output: indicator LEDs - .{ .data = .{ - .usage = .{ .global_page = .led }, - .usage_range = .{ 1, 5 }, - .count = 5, - .Child = bool, - .dir = .out, - .type = .dynamic, - } }, - // Padding - .{ .data_static = .{ .out, u3 } }, - // Input: up to 6 pressed key codes - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0x00, 0xff }, - .count = 6, - .Child = u8, - .dir = .in, - .type = .selector, - } }, - // End - .main_collection_end, + .itf_string = "Boot Keyboard", + .poll_interval = 1, + .generic_runtime = .{ + .report_descriptor = &.{ + .{ .global_usage_page = .generic_desktop }, + .local_usage_enum(.{ .generic_desktop = .keyboard }), + .{ .main_collection = .Application }, + // Input: modifier key bitmap + .{ .data = .{ + .usage = .{ .global_page = .keyboard }, + .usage_range = .{ 0xE0, 0xE7 }, + .count = 8, + .Child = bool, + .dir = .in, + .type = .dynamic, + } }, + // Reserved 8 bits + .{ .data_static = .{ .in, u8 } }, + // Output: indicator LEDs + .{ .data = .{ + .usage = .{ .global_page = .led }, + .usage_range = .{ 1, 5 }, + .count = 5, + .Child = bool, + .dir = .out, + .type = .dynamic, + } }, + // Padding + .{ .data_static = .{ .out, u3 } }, + // Input: up to 6 pressed key codes + .{ .data = .{ + .usage = .{ .global_page = .keyboard }, + .usage_range = .{ 0x00, 0xff }, + .count = 6, + .Child = u8, + .dir = .in, + .type = .selector, + } }, + // End + .main_collection_end, + }, + .InReport = KeyboardInReport, + .OutReport = KeyboardOutReport, }, - .InReport = KeyboardInReport, - .OutReport = KeyboardOutReport, -}); +}; var usb_device: USBD = undefined; @@ -137,9 +141,9 @@ var usb_controller: usb.DeviceController(.{ .max_supported_packet_size = USBD.max_supported_packet_size, }, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, - struct { keyboard: Keyboard }, + struct { keyboard: usb.drivers.HID_Interrupt }, .{ - .keyboard = .{ .itf_string = "Boot Keyboard", .poll_interval = 1 }, + .keyboard = hid_driver_options, }, )}) = .init; diff --git a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig index 660d39944..4abfefbaa 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig @@ -104,7 +104,7 @@ var usb_tx_buff: [1024]u8 = undefined; /// Transfer data to host /// NOTE: After each USB chunk transfer, we have to call the USB task so that bus TX events can be /// handled -pub fn usb_cdc_write(serial: *USB_Serial, comptime fmt: []const u8, args: anytype) void { +pub fn usb_cdc_write(serial: *USB_Serial.Runtime, comptime fmt: []const u8, args: anytype) void { var tx = std.fmt.bufPrint(&usb_tx_buff, fmt, args) catch &.{}; while (tx.len > 0) { @@ -121,7 +121,7 @@ var usb_rx_buff: [1024]u8 = undefined; /// Receive data from host /// NOTE: Read code was not tested extensively. In case of issues, try to call USB task before every /// read operation -pub fn usb_cdc_read(serial: *USB_Serial) []const u8 { +pub fn usb_cdc_read(serial: *USB_Serial.Runtime) []const u8 { var rx_len: usize = 0; while (true) { diff --git a/examples/raspberrypi/rp2xxx/src/usb_hid.zig b/examples/raspberrypi/rp2xxx/src/usb_hid.zig index 2617735e6..1f15e299a 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_hid.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_hid.zig @@ -73,50 +73,54 @@ pub const KeyboardOutReport = packed struct(u8) { padding: u5 = 0, }; -const Keyboard = usb.drivers.hid.InterruptDriver(.{ +const hid_driver_options: usb.drivers.HID_Interrupt = .{ .subclass = .Boot, .protocol = .Boot, - .report_descriptor = &.{ - .{ .global_usage_page = .generic_desktop }, - .local_usage_enum(.{ .generic_desktop = .keyboard }), - .{ .main_collection = .Application }, - // Input: modifier key bitmap - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0xE0, 0xE7 }, - .count = 8, - .Child = bool, - .dir = .in, - .type = .dynamic, - } }, - // Reserved 8 bits - .{ .data_static = .{ .in, u8 } }, - // Output: indicator LEDs - .{ .data = .{ - .usage = .{ .global_page = .led }, - .usage_range = .{ 1, 5 }, - .count = 5, - .Child = bool, - .dir = .out, - .type = .dynamic, - } }, - // Padding - .{ .data_static = .{ .out, u3 } }, - // Input: up to 6 pressed key codes - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0x00, 0xff }, - .count = 6, - .Child = u8, - .dir = .in, - .type = .selector, - } }, - // End - .main_collection_end, + .itf_string = "Boot Keyboard", + .poll_interval = 1, + .generic_runtime = .{ + .report_descriptor = &.{ + .{ .global_usage_page = .generic_desktop }, + .local_usage_enum(.{ .generic_desktop = .keyboard }), + .{ .main_collection = .Application }, + // Input: modifier key bitmap + .{ .data = .{ + .usage = .{ .global_page = .keyboard }, + .usage_range = .{ 0xE0, 0xE7 }, + .count = 8, + .Child = bool, + .dir = .in, + .type = .dynamic, + } }, + // Reserved 8 bits + .{ .data_static = .{ .in, u8 } }, + // Output: indicator LEDs + .{ .data = .{ + .usage = .{ .global_page = .led }, + .usage_range = .{ 1, 5 }, + .count = 5, + .Child = bool, + .dir = .out, + .type = .dynamic, + } }, + // Padding + .{ .data_static = .{ .out, u3 } }, + // Input: up to 6 pressed key codes + .{ .data = .{ + .usage = .{ .global_page = .keyboard }, + .usage_range = .{ 0x00, 0xff }, + .count = 6, + .Child = u8, + .dir = .in, + .type = .selector, + } }, + // End + .main_collection_end, + }, + .InReport = KeyboardInReport, + .OutReport = KeyboardOutReport, }, - .InReport = KeyboardInReport, - .OutReport = KeyboardOutReport, -}); +}; var usb_device: USB_Device = undefined; @@ -130,9 +134,12 @@ var usb_controller: usb.DeviceController(.{ .max_supported_packet_size = USB_Device.max_supported_packet_size, }, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, - struct { keyboard: Keyboard, reset: rp2xxx.usb.ResetDriver(null, 0) }, + struct { + keyboard: usb.drivers.HID_Interrupt, + reset: rp2xxx.usb.ResetDriver(null, 0), + }, .{ - .keyboard = .{ .itf_string = "Boot Keyboard", .poll_interval = 1 }, + .keyboard = hid_driver_options, .reset = "", }, )}) = .init; diff --git a/examples/wch/ch32v/src/usb_cdc.zig b/examples/wch/ch32v/src/usb_cdc.zig index 19a4d5708..caf00fec9 100644 --- a/examples/wch/ch32v/src/usb_cdc.zig +++ b/examples/wch/ch32v/src/usb_cdc.zig @@ -89,7 +89,7 @@ var usb_tx_buff: [1024]u8 = undefined; // Transfer data to host // NOTE: After each USB chunk transfer, we have to call the USB task so that bus TX events can be handled -pub fn usb_cdc_write(serial: *USB_Serial, comptime fmt: []const u8, args: anytype) void { +pub fn usb_cdc_write(serial: *USB_Serial.Runtime, comptime fmt: []const u8, args: anytype) void { const text = std.fmt.bufPrint(&usb_tx_buff, fmt, args) catch &.{}; var write_buff = text; while (write_buff.len > 0) { @@ -105,7 +105,7 @@ var usb_rx_buff: [1024]u8 = undefined; // Receive data from host // NOTE: Read code was not tested extensively. In case of issues, try to call USB task before every read operation pub fn usb_cdc_read( - serial: *USB_Serial, + serial: *USB_Serial.Runtime, ) []const u8 { var total_read: usize = 0; var read_buff: []u8 = usb_rx_buff[0..]; diff --git a/port/nordic/nrf5x/src/hal/usbd.zig b/port/nordic/nrf5x/src/hal/usbd.zig index 711ecd1f7..670b333a2 100644 --- a/port/nordic/nrf5x/src/hal/usbd.zig +++ b/port/nordic/nrf5x/src/hal/usbd.zig @@ -52,8 +52,8 @@ pub const USBD = struct { pub const max_supported_packet_size = MAX_PACKET_SIZE; pub const max_supported_bcd_usb: usb.types.Version = .v1_10; - pub const default_vendor_id: usb.Config.IdStringPair = .{ .id = 0x1209, .str = "pid.codes" }; - pub const default_product_id: usb.Config.IdStringPair = .{ .id = 0x0001, .str = "nRF5x test device" }; + pub const default_vendor_id: usb.Options.IdStringPair = .{ .id = 0x1209, .str = "pid.codes" }; + pub const default_product_id: usb.Options.IdStringPair = .{ .id = 0x0001, .str = "nRF5x test device" }; const vtable: usb.DeviceInterface.VTable = .{ .ep_writev = ep_writev, diff --git a/port/raspberrypi/rp2xxx/src/hal/usb.zig b/port/raspberrypi/rp2xxx/src/hal/usb.zig index 63e090a93..fc6de87e7 100644 --- a/port/raspberrypi/rp2xxx/src/hal/usb.zig +++ b/port/raspberrypi/rp2xxx/src/hal/usb.zig @@ -471,33 +471,35 @@ pub fn ResetDriver(bootsel_activity_led: ?u5, interface_disable_mask: u32) type } }; - pub fn init(self: *@This(), desc: *const Descriptor, device: *usb.DeviceInterface) void { - _ = desc; - _ = device; - self.* = .{}; - } + pub const Runtime = struct { + pub fn init(self: *@This(), desc: *const Descriptor, device: *usb.DeviceInterface) void { + _ = desc; + _ = device; + self.* = .{}; + } - pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { - _ = self; - switch (setup.request) { - 0x01 => { - const value = setup.value.native(); - const mask = @as(u32, 1) << if (value & 0x100 != 0) - @intCast(value >> 9) - else - bootsel_activity_led orelse 0; - const itf_disable = (value & 0x7F) | interface_disable_mask; - log_drv.debug("Resetting to bootsel. Mask: {} Itf disable: {}", .{ mask, itf_disable }); - microzig.hal.rom.reset_to_usb_boot(); - }, - 0x02 => { - log_drv.debug("Resetting to flash", .{}); - // Not implemented yet - microzig.hal.rom.reset_to_usb_boot(); - }, - else => return usb.nak, + pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { + _ = self; + switch (setup.request) { + 0x01 => { + const value = setup.value.native(); + const mask = @as(u32, 1) << if (value & 0x100 != 0) + @intCast(value >> 9) + else + bootsel_activity_led orelse 0; + const itf_disable = (value & 0x7F) | interface_disable_mask; + log_drv.debug("Resetting to bootsel. Mask: {} Itf disable: {}", .{ mask, itf_disable }); + microzig.hal.rom.reset_to_usb_boot(); + }, + 0x02 => { + log_drv.debug("Resetting to flash", .{}); + // Not implemented yet + microzig.hal.rom.reset_to_usb_boot(); + }, + else => return usb.nak, + } + return usb.ack; } - return usb.ack; - } + }; }; } From fe3c7a12cbff65cbdeadce94e569e64912a857d0 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Wed, 11 Nov 2026 02:26:18 +0100 Subject: [PATCH 10/28] Add usb echo example --- examples/raspberrypi/rp2xxx/build.zig | 1 + .../raspberrypi/rp2xxx/src/usb_raw_echo.zig | 83 +++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig diff --git a/examples/raspberrypi/rp2xxx/build.zig b/examples/raspberrypi/rp2xxx/build.zig index a16987076..08747e494 100644 --- a/examples/raspberrypi/rp2xxx/build.zig +++ b/examples/raspberrypi/rp2xxx/build.zig @@ -86,6 +86,7 @@ pub fn build(b: *std.Build) void { .{ .name = "stepper_driver_dumb", .file = "src/stepper_driver_dumb.zig" }, .{ .name = "usb-hid", .file = "src/usb_hid.zig" }, .{ .name = "usb-cdc", .file = "src/usb_cdc.zig" }, + .{ .name = "usb-raw-echo", .file = "src/usb_raw_echo.zig" }, .{ .name = "dma", .file = "src/dma.zig" }, .{ .name = "cyw43", .file = "src/cyw43.zig" }, .{ .name = "cyw43-blinky", .file = "src/cyw43/blinky.zig" }, diff --git a/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig b/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig new file mode 100644 index 000000000..35716798f --- /dev/null +++ b/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig @@ -0,0 +1,83 @@ +const std = @import("std"); +const microzig = @import("microzig"); + +const rp2xxx = microzig.hal; +const time = rp2xxx.time; +const usb = microzig.core.usb; +// Port-specific type which implements the DeviceInterface interface, used by the USB core to +// read from/write to the peripheral. +const USB_Device = rp2xxx.usb.Polled(.{}); + +var usb_device: USB_Device = undefined; + +// Generate a device controller with descriptor and handlers setup for CDC (USB_Serial) and +// picotool-controlled reset (ResetDriver). +var usb_controller: usb.DeviceController(.{ + .bcd_usb = USB_Device.max_supported_bcd_usb, + .device_triple = .unspecified, + .vendor = USB_Device.default_vendor_id, + .product = USB_Device.default_product_id, + .bcd_device = .v1_00, + .serial = "someserial", + .max_supported_packet_size = USB_Device.max_supported_packet_size, +}, &.{usb.Configuration( + .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, + struct { echo: usb.drivers.EchoExample, reset: rp2xxx.usb.ResetDriver(null, 0) }, + .{ .echo = "", .reset = "" }, +)}) = .init; + +pub const std_options = microzig.std_options(.{ + .log_level = .debug, + .log_scope_levels = &.{ + .{ .scope = .usb_dev, .level = .warn }, + .{ .scope = .usb_ctrl, .level = .warn }, + .{ .scope = .usb_echo, .level = .warn }, + }, + .logFn = rp2xxx.uart.log, +}); + +comptime { + _ = microzig.export_startup(); +} + +pub fn panic(message: []const u8, _: ?*std.builtin.StackTrace, _: ?usize) noreturn { + std.log.err("panic: {s}", .{message}); + @breakpoint(); + while (true) {} +} + +const pin_config: rp2xxx.pins.GlobalConfiguration = .{ + .GPIO25 = .{ .name = "led", .direction = .out }, +}; + +pub fn main() !void { + const pins = pin_config.apply(); + + const uart = rp2xxx.uart.instance.num(0); + uart.apply(.{ + .clock_config = rp2xxx.clock_config, + }); + rp2xxx.uart.init_logger(uart); + + pins.led.put(1); + + // Then initialize the USB device using the configuration defined above + usb_device = .init(); + + var old: u64 = time.get_time_since_boot().to_us(); + var new: u64 = 0; + + while (true) { + // You can now poll for USB events + usb_device.poll(&usb_controller); + + // Ensure that the host as finished enumerating our USB device + if (usb_controller.drivers()) |_| { + new = time.get_time_since_boot().to_us(); + if (new - old > 500_000) { + old = new; + pins.led.toggle(); + } + } + } +} From 540c1fdd2d9abe7ec797e7f75a7f81f894e8e751 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Wed, 11 Nov 2026 03:14:22 +0100 Subject: [PATCH 11/28] Redo USB Driver declaration API --- core/src/core/usb.zig | 81 +++++++++++-------- core/src/core/usb/drivers/CDC.zig | 14 ++-- core/src/core/usb/drivers/EchoExample.zig | 13 +-- examples/nordic/nrf5x/src/usb_cdc.zig | 13 +-- examples/nordic/nrf5x/src/usb_hid.zig | 5 +- examples/raspberrypi/rp2xxx/src/usb_cdc.zig | 12 ++- examples/raspberrypi/rp2xxx/src/usb_hid.zig | 6 +- .../raspberrypi/rp2xxx/src/usb_raw_echo.zig | 6 +- examples/wch/ch32v/src/usb_cdc.zig | 5 +- port/raspberrypi/rp2xxx/src/hal/usb.zig | 7 +- 10 files changed, 81 insertions(+), 81 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index 0c87013a4..13b26fdfc 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -169,28 +169,29 @@ pub const ConfigurationOptions = struct { pub fn Configuration( options: ConfigurationOptions, - Drivers: type, - driver_args: blk: { - const info = @typeInfo(Drivers).@"struct"; - const count = info.field_names.len; - var field_names: [count][:0]const u8 = undefined; - var field_types: [count]type = undefined; - for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { - // Collect field names - field_names[i] = field_name; - // Collect the type info for the Descriptor.create function parameter - const param_types = @typeInfo(@TypeOf(field_type.Descriptor.create)).@"fn".param_types; - // Ensure it takes 3 parameters - assert(param_types.len == 3); - // The first must be a DescriptorAllocator - assert(param_types[0] == *DescriptorAllocator); - // The second is usb.types.PacketLength - assert(param_types[1] == types.PacketLength); - // And save the type of the third - field_types[i] = param_types[2].?; - } - break :blk @Struct(.auto, null, &field_names, &field_types, &@splat(.{})); - }, + driver_config: anytype, + // driver_args: blk: { + // const info = @typeInfo(Drivers).@"struct"; + // const count = info.field_names.len; + // var field_names: [count][:0]const u8 = undefined; + // var field_types: [count]type = undefined; + // for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { + // // Collect field names + // field_names[i] = field_name; + // // Collect the type info for the Descriptor.create function parameter + // const param_types = @typeInfo(@TypeOf(field_type.Descriptor.create)).@"fn".param_types; + // // Ensure it takes 3 parameters + // assert(param_types.len == 3); + // // The first must be a DescriptorAllocator + // assert(param_types[0] == *DescriptorAllocator); + // // The second is usb.types.PacketLength + // assert(param_types[1] == types.PacketLength); + // // And save the type of the third + // assert(param_types[2] == field_type); + // field_types[i] = param_types[2].?; + // } + // break :blk @Struct(.auto, null, &field_names, &field_types, &@splat(.{})); + // }, ) type { return struct { const DriverName = []const u8; @@ -205,12 +206,12 @@ pub fn Configuration( pub fn create(max_psize: types.PacketLength, strings: []const []const u8) struct { @This(), []const []const u8 } { var alloc = DescriptorAllocator.init(options.unique_endpoints, strings); const configuration_s = alloc.string(options.name); - const driver_info = @typeInfo(Drivers).@"struct"; + const driver_info = @typeInfo(@TypeOf(driver_config)).@"struct"; + const driver_field_names = driver_info.field_names; - var field_names: [driver_info.field_names.len][:0]const u8 = undefined; - var desc_field_types: [driver_info.field_names.len]type = undefined; - var runtime_field_types: [driver_info.field_names.len]type = undefined; - var field_attrs: [driver_info.field_names.len]std.builtin.Type.Struct.FieldAttributes = undefined; + var desc_field_types: [driver_field_names.len]type = undefined; + var runtime_field_types: [driver_field_names.len]type = undefined; + var field_attrs: [driver_field_names.len]std.builtin.Type.Struct.FieldAttributes = undefined; var ep_handler_types: [2][16]type = @splat(@splat(void)); var ep_handler_names: [2][16][:0]const u8 = undefined; var ep_handler_drivers: [2][16]?usize = @splat(@splat(null)); @@ -219,16 +220,16 @@ pub fn Configuration( var driver_alloc_types: []const type = &.{}; var driver_alloc_attrs: []const std.builtin.Type.Struct.FieldAttributes = &.{}; - for (driver_info.field_names, driver_info.field_types, 0..) |driver_field_name, DriverType, drv_id| { + for (driver_field_names, driver_info.field_types, 0..) |driver_field_name, DriverType, drv_id| { runtime_field_types[drv_id] = if (@hasField(DriverType, "generic_runtime")) - DriverType.Runtime(@field(driver_args, driver_field_name).generic_runtime) + DriverType.Runtime(@field(driver_config, driver_field_name).generic_runtime) else DriverType.Runtime; // Get descriptor type for the current driver const Descriptors = DriverType.Descriptor; // Call the create method on the descriptor, which wraps it with the allow stuff. - const result = Descriptors.create(&alloc, max_psize, @field(driver_args, driver_field_name)); + const result = Descriptors.create(&alloc, max_psize, @field(driver_config, driver_field_name)); // Get the descriptor instance from the result. const descriptors = result.descriptor; @@ -290,7 +291,6 @@ pub fn Configuration( else => {}, } } - field_names[drv_id] = driver_field_name; desc_field_types[drv_id] = Descriptors; field_attrs[drv_id] = .{ .default_value_ptr = &descriptors }; } @@ -311,7 +311,14 @@ pub fn Configuration( const const_alloc = alloc.to_const(); const const_ep_handlers = ep_handlers; - const DriverConfig = @Struct(.@"extern", null, &field_names, &desc_field_types, &field_attrs); + const DriverConfig = @Struct( + .@"extern", + null, + driver_field_names, + &desc_field_types, + &field_attrs, + ); + const Descriptor = extern struct { first: descriptor.Configuration = .{ .total_length = .from(@sizeOf(descriptor.Configuration) + @sizeOf(DriverConfig)), @@ -345,7 +352,7 @@ pub fn Configuration( var ret: @FieldType(@This(), "drivers_ep") = undefined; for (&ret, ep_handler_drivers) |*dstv, srcv| { for (dstv, srcv) |*dst, src_opt| { - dst.* = if (src_opt) |src| field_names[src] else null; + dst.* = if (src_opt) |src| driver_field_names[src] else null; } } break :blk ret; @@ -355,7 +362,13 @@ pub fn Configuration( out: ep_handlers_types[idx_out] = const_ep_handlers[idx_out], }, .handlers_itf = handlers_itf, - .RuntimeData = @Struct(.auto, null, &field_names, &runtime_field_types, &@splat(.{})), + .RuntimeData = @Struct( + .auto, + null, + driver_field_names, + &runtime_field_types, + &@splat(.{}), + ), }, const_alloc.strings, }; diff --git a/core/src/core/usb/drivers/CDC.zig b/core/src/core/usb/drivers/CDC.zig index 5c8cae8a7..1efbca24a 100644 --- a/core/src/core/usb/drivers/CDC.zig +++ b/core/src/core/usb/drivers/CDC.zig @@ -57,6 +57,9 @@ pub const LineCoding = extern struct { const CDC_Driver = @This(); +itf_notifi_str: []const u8 = "", +itf_data_str: []const u8 = "", + // This struct bundles all the descriptors CDC needs into one Configuration. pub const Descriptor = extern struct { const desc = usb.descriptor; @@ -72,11 +75,6 @@ pub const Descriptor = extern struct { ep_out: desc.Endpoint, ep_in: desc.Endpoint, - const Strings = struct { - itf_notifi: []const u8 = "", - itf_data: []const u8 = "", - }; - /// This function is used during descriptor creation. Endpoint and interface numbers are /// allocated through the `alloc` parameter. Third argument can be of any type, it's passed /// by the user when creating the device controller type. If multiple instances of a driver @@ -85,7 +83,7 @@ pub const Descriptor = extern struct { pub fn create( alloc: *usb.DescriptorAllocator, max_supported_packet_size: usb.types.PacketLength, - strings: Strings, + options: CDC_Driver, ) usb.DescriptorCreateResult(@This()) { // Endpoint and interface numbers are allocated through the `alloc` parameter, // so that multiple instances of this driver can coexist. @@ -106,7 +104,7 @@ pub const Descriptor = extern struct { .alternate_setting = 0, .num_endpoints = 1, .interface_triple = .from(.CDC, .Abstract, .NoneRequired), - .interface_s = alloc.string(strings.itf_notifi), + .interface_s = alloc.string(options.itf_notifi_str), }, .cdc_header = .{ .bcd_cdc = .from(1, 20) }, .cdc_call_mgmt = .{ @@ -140,7 +138,7 @@ pub const Descriptor = extern struct { .alternate_setting = 0, .num_endpoints = 2, .interface_triple = .from(.CDC_Data, .Unused, .NoneRequired), - .interface_s = alloc.string(strings.itf_data), + .interface_s = alloc.string(options.itf_data_str), }, .ep_out = .bulk(alloc.next_ep(.out), max_supported_packet_size), .ep_in = .bulk(alloc.next_ep(.in), max_supported_packet_size), diff --git a/core/src/core/usb/drivers/EchoExample.zig b/core/src/core/usb/drivers/EchoExample.zig index 79898aecf..508987ecd 100644 --- a/core/src/core/usb/drivers/EchoExample.zig +++ b/core/src/core/usb/drivers/EchoExample.zig @@ -6,6 +6,8 @@ const log = std.log.scoped(.usb_echo); pub const EchoExampleDriver = @This(); +itf_string: []const u8 = "", + /// The descriptors need to have the same memory layout as the sent data. pub const Descriptor = extern struct { const desc = usb.descriptor; @@ -15,14 +17,13 @@ pub const Descriptor = extern struct { ep_in: desc.Endpoint, /// This function is used during descriptor creation. Endpoint and interface numbers are - /// allocated through the `alloc` parameter. Third argument can be of any type, it's passed - /// by the user when creating the device controller type. If multiple instances of a driver - /// are used, this function is called for each, with different arguments. Passing arguments - /// through this function is preffered to making the whole driver generic. + /// allocated through the `alloc` parameter. Third argument contains driver configuration. + /// If multiple instances of a driver are used, this function is called for each, + /// with different arguments. pub fn create( alloc: *usb.DescriptorAllocator, max_supported_packet_size: usb.types.PacketLength, - itf_string: []const u8, + options: EchoExampleDriver, ) usb.DescriptorCreateResult(@This()) { return .{ .descriptor = .{ @@ -31,7 +32,7 @@ pub const Descriptor = extern struct { .alternate_setting = 0, .num_endpoints = 2, .interface_triple = .vendor_specific, - .interface_s = alloc.string(itf_string), + .interface_s = alloc.string(options.itf_string), }, .ep_out = .bulk(alloc.next_ep(.out), max_supported_packet_size), .ep_in = .bulk(alloc.next_ep(.in), max_supported_packet_size), diff --git a/examples/nordic/nrf5x/src/usb_cdc.zig b/examples/nordic/nrf5x/src/usb_cdc.zig index f63030db9..0b103e4f9 100644 --- a/examples/nordic/nrf5x/src/usb_cdc.zig +++ b/examples/nordic/nrf5x/src/usb_cdc.zig @@ -11,8 +11,6 @@ const USBD = nrf.usbd.USBD; const clocks = nrf.clocks; const uart = nrf.uart.num(0); -const USB_Serial = usb.drivers.CDC; - pub const panic = microzig.panic; pub const std_options = microzig.std_options(.{ @@ -31,7 +29,7 @@ comptime { var usb_device: USBD = undefined; -// Generate a device controller with descriptor and handlers setup for CDC (USB_Serial) +// Generate a device controller with descriptor and handlers setup for CDC (usb.drivers.CDC) var usb_controller: usb.DeviceController(.{ .bcd_usb = USBD.max_supported_bcd_usb, .device_triple = .unspecified, @@ -42,10 +40,7 @@ var usb_controller: usb.DeviceController(.{ .max_supported_packet_size = USBD.max_supported_packet_size, }, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, - struct { serial: USB_Serial }, - .{ - .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, - }, + .{ .serial = usb.drivers.CDC{ .itf_notifi_str = "Board CDC", .itf_data_str = "Board CDC Data" } }, )}) = .init; pub fn main() !void { @@ -96,7 +91,7 @@ var usb_tx_buff: [1024]u8 = undefined; /// Transfer data to host /// NOTE: After each USB chunk transfer, we have to call the USB task so that bus TX events can be /// handled -pub fn usb_cdc_write(serial: *USB_Serial.Runtime, comptime fmt: []const u8, args: anytype) void { +pub fn usb_cdc_write(serial: *usb.drivers.CDC.Runtime, comptime fmt: []const u8, args: anytype) void { var tx = std.fmt.bufPrint(&usb_tx_buff, fmt, args) catch &.{}; while (tx.len > 0) { @@ -113,7 +108,7 @@ var usb_rx_buff: [1024]u8 = undefined; /// Receive data from host /// NOTE: Read code was not tested extensively. In case of issues, try to call USB task before every /// read operation -pub fn usb_cdc_read(serial: *USB_Serial.Runtime) []const u8 { +pub fn usb_cdc_read(serial: *usb.drivers.CDC.Runtime) []const u8 { var rx_len: usize = 0; while (true) { diff --git a/examples/nordic/nrf5x/src/usb_hid.zig b/examples/nordic/nrf5x/src/usb_hid.zig index c1618a6bf..2d386d981 100644 --- a/examples/nordic/nrf5x/src/usb_hid.zig +++ b/examples/nordic/nrf5x/src/usb_hid.zig @@ -141,10 +141,7 @@ var usb_controller: usb.DeviceController(.{ .max_supported_packet_size = USBD.max_supported_packet_size, }, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, - struct { keyboard: usb.drivers.HID_Interrupt }, - .{ - .keyboard = hid_driver_options, - }, + .{ .keyboard = hid_driver_options }, )}) = .init; pub fn main() !void { diff --git a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig index 4abfefbaa..bb7ce9eec 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig @@ -8,11 +8,10 @@ const usb = microzig.core.usb; // read from/write to the peripheral. const USB_Device = rp2xxx.usb.Polled(.{}); // USB class driver -const USB_Serial = usb.drivers.CDC; var usb_device: USB_Device = undefined; -// Generate a device controller with descriptor and handlers setup for CDC (USB_Serial) and +// Generate a device controller with descriptor and handlers setup for CDC (usb.drivers.CDC) and // picotool-controlled reset (ResetDriver). var usb_controller: usb.DeviceController(.{ .bcd_usb = USB_Device.max_supported_bcd_usb, @@ -24,10 +23,9 @@ var usb_controller: usb.DeviceController(.{ .max_supported_packet_size = USB_Device.max_supported_packet_size, }, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, - struct { serial: USB_Serial, reset: rp2xxx.usb.ResetDriver(null, 0) }, .{ - .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, - .reset = "", + .serial = usb.drivers.CDC{ .itf_notifi_str = "Board CDC", .itf_data_str = "Board CDC Data" }, + .reset = rp2xxx.usb.ResetDriver(null, 0){}, }, )}) = .init; @@ -104,7 +102,7 @@ var usb_tx_buff: [1024]u8 = undefined; /// Transfer data to host /// NOTE: After each USB chunk transfer, we have to call the USB task so that bus TX events can be /// handled -pub fn usb_cdc_write(serial: *USB_Serial.Runtime, comptime fmt: []const u8, args: anytype) void { +pub fn usb_cdc_write(serial: *usb.drivers.CDC.Runtime, comptime fmt: []const u8, args: anytype) void { var tx = std.fmt.bufPrint(&usb_tx_buff, fmt, args) catch &.{}; while (tx.len > 0) { @@ -121,7 +119,7 @@ var usb_rx_buff: [1024]u8 = undefined; /// Receive data from host /// NOTE: Read code was not tested extensively. In case of issues, try to call USB task before every /// read operation -pub fn usb_cdc_read(serial: *USB_Serial.Runtime) []const u8 { +pub fn usb_cdc_read(serial: *usb.drivers.CDC.Runtime) []const u8 { var rx_len: usize = 0; while (true) { diff --git a/examples/raspberrypi/rp2xxx/src/usb_hid.zig b/examples/raspberrypi/rp2xxx/src/usb_hid.zig index 1f15e299a..b6c987211 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_hid.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_hid.zig @@ -134,13 +134,9 @@ var usb_controller: usb.DeviceController(.{ .max_supported_packet_size = USB_Device.max_supported_packet_size, }, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, - struct { - keyboard: usb.drivers.HID_Interrupt, - reset: rp2xxx.usb.ResetDriver(null, 0), - }, .{ .keyboard = hid_driver_options, - .reset = "", + .reset = rp2xxx.usb.ResetDriver(null, 0){}, }, )}) = .init; diff --git a/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig b/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig index 35716798f..eeaecaf3e 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig @@ -22,8 +22,10 @@ var usb_controller: usb.DeviceController(.{ .max_supported_packet_size = USB_Device.max_supported_packet_size, }, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, - struct { echo: usb.drivers.EchoExample, reset: rp2xxx.usb.ResetDriver(null, 0) }, - .{ .echo = "", .reset = "" }, + .{ + .echo = usb.drivers.EchoExample{}, + .reset = rp2xxx.usb.ResetDriver(null, 0){}, + }, )}) = .init; pub const std_options = microzig.std_options(.{ diff --git a/examples/wch/ch32v/src/usb_cdc.zig b/examples/wch/ch32v/src/usb_cdc.zig index caf00fec9..b50d7ec8e 100644 --- a/examples/wch/ch32v/src/usb_cdc.zig +++ b/examples/wch/ch32v/src/usb_cdc.zig @@ -33,10 +33,7 @@ const USB_Controller = usb.DeviceController(.{ .max_supported_packet_size = hal.usb.max_packet_size, }, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, - struct { serial: USB_Serial }, - .{ - .serial = .{ .itf_notifi = "Board CDC", .itf_data = "Board CDC Data" }, - }, + .{ .serial = usb.drivers.CDC{ .itf_notifi_str = "Board CDC", .itf_data_str = "Board CDC Data" } }, )}); pub var usb_dev: hal.usb.Polled(board.usb_setup, .{}) = undefined; diff --git a/port/raspberrypi/rp2xxx/src/hal/usb.zig b/port/raspberrypi/rp2xxx/src/hal/usb.zig index fc6de87e7..926184f31 100644 --- a/port/raspberrypi/rp2xxx/src/hal/usb.zig +++ b/port/raspberrypi/rp2xxx/src/hal/usb.zig @@ -448,6 +448,9 @@ pub fn Polled(config: Config) type { pub fn ResetDriver(bootsel_activity_led: ?u5, interface_disable_mask: u32) type { return struct { const log_drv = std.log.scoped(.pico_reset); + const Options = @This(); + + itf_string: []const u8 = "", pub const Descriptor = extern struct { reset_interface: usb.descriptor.Interface, @@ -455,7 +458,7 @@ pub fn ResetDriver(bootsel_activity_led: ?u5, interface_disable_mask: u32) type pub fn create( alloc: *usb.DescriptorAllocator, _: usb.types.PacketLength, - interface_str: []const u8, + options: Options, ) usb.DescriptorCreateResult(@This()) { return .{ .descriptor = .{ .reset_interface = .{ .interface_number = alloc.next_itf(), @@ -466,7 +469,7 @@ pub fn ResetDriver(bootsel_activity_led: ?u5, interface_disable_mask: u32) type @fromBackingInt(0x00), @fromBackingInt(0x01), ), - .interface_s = alloc.string(interface_str), + .interface_s = alloc.string(options.itf_string), } } }; } }; From a3a2f6f4ac39832019d73ac2c77212a4801e61a8 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Wed, 11 Nov 2026 03:40:46 +0100 Subject: [PATCH 12/28] Move usb.Configuration into a separate file --- core/src/core/usb.zig | 254 +---------------- core/src/core/usb/configuration.zig | 259 ++++++++++++++++++ examples/nordic/nrf5x/src/usb_cdc.zig | 2 +- examples/nordic/nrf5x/src/usb_hid.zig | 2 +- examples/raspberrypi/rp2xxx/src/usb_cdc.zig | 2 +- examples/raspberrypi/rp2xxx/src/usb_hid.zig | 2 +- .../raspberrypi/rp2xxx/src/usb_raw_echo.zig | 2 +- examples/wch/ch32v/src/usb_cdc.zig | 2 +- 8 files changed, 266 insertions(+), 259 deletions(-) create mode 100644 core/src/core/usb/configuration.zig diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index 13b26fdfc..b913c6502 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -2,6 +2,7 @@ const std = @import("std"); const assert = std.debug.assert; const log = std.log.scoped(.usb_ctrl); +pub const configuration = @import("usb/configuration.zig"); pub const descriptor = @import("usb/descriptor.zig"); pub const drivers = struct { pub const CDC = @import("usb/drivers/CDC.zig"); @@ -157,259 +158,6 @@ pub const Options = struct { max_supported_packet_size: types.PacketLength, }; -pub const ConfigurationOptions = struct { - attributes: descriptor.Configuration.Attributes, - max_current_ma: u9, - name: []const u8 = "", - /// Only use either IN or OUT on each endpoint. Useful for debugging. - /// Realistically, it should only be turned off if you are exhausting - /// the 15 endpoint limit. - unique_endpoints: bool = true, -}; - -pub fn Configuration( - options: ConfigurationOptions, - driver_config: anytype, - // driver_args: blk: { - // const info = @typeInfo(Drivers).@"struct"; - // const count = info.field_names.len; - // var field_names: [count][:0]const u8 = undefined; - // var field_types: [count]type = undefined; - // for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { - // // Collect field names - // field_names[i] = field_name; - // // Collect the type info for the Descriptor.create function parameter - // const param_types = @typeInfo(@TypeOf(field_type.Descriptor.create)).@"fn".param_types; - // // Ensure it takes 3 parameters - // assert(param_types.len == 3); - // // The first must be a DescriptorAllocator - // assert(param_types[0] == *DescriptorAllocator); - // // The second is usb.types.PacketLength - // assert(param_types[1] == types.PacketLength); - // // And save the type of the third - // assert(param_types[2] == field_type); - // field_types[i] = param_types[2].?; - // } - // break :blk @Struct(.auto, null, &field_names, &field_types, &@splat(.{})); - // }, -) type { - return struct { - const DriverName = []const u8; - - Descriptor: type, - DriverAlloc: type, - drivers_ep: [2][16]?DriverName, - HandlersEp: type, - handlers_itf: []const DriverName, - RuntimeData: type, - - pub fn create(max_psize: types.PacketLength, strings: []const []const u8) struct { @This(), []const []const u8 } { - var alloc = DescriptorAllocator.init(options.unique_endpoints, strings); - const configuration_s = alloc.string(options.name); - const driver_info = @typeInfo(@TypeOf(driver_config)).@"struct"; - const driver_field_names = driver_info.field_names; - - var desc_field_types: [driver_field_names.len]type = undefined; - var runtime_field_types: [driver_field_names.len]type = undefined; - var field_attrs: [driver_field_names.len]std.builtin.Type.Struct.FieldAttributes = undefined; - var ep_handler_types: [2][16]type = @splat(@splat(void)); - var ep_handler_names: [2][16][:0]const u8 = undefined; - var ep_handler_drivers: [2][16]?usize = @splat(@splat(null)); - var handlers_itf: []const DriverName = &.{}; - var driver_alloc_names: []const [:0]const u8 = &.{}; - var driver_alloc_types: []const type = &.{}; - var driver_alloc_attrs: []const std.builtin.Type.Struct.FieldAttributes = &.{}; - - for (driver_field_names, driver_info.field_types, 0..) |driver_field_name, DriverType, drv_id| { - runtime_field_types[drv_id] = if (@hasField(DriverType, "generic_runtime")) - DriverType.Runtime(@field(driver_config, driver_field_name).generic_runtime) - else - DriverType.Runtime; - - // Get descriptor type for the current driver - const Descriptors = DriverType.Descriptor; - // Call the create method on the descriptor, which wraps it with the allow stuff. - const result = Descriptors.create(&alloc, max_psize, @field(driver_config, driver_field_name)); - // Get the descriptor instance from the result. - const descriptors = result.descriptor; - - // If the driver requests memory, then collect the names, types, and attrs - if (result.alloc_bytes) |len| { - driver_alloc_names = driver_alloc_names ++ &[_][:0]const u8{driver_field_name}; - driver_alloc_types = driver_alloc_types ++ &[_]type{[len]u8}; - driver_alloc_attrs = driver_alloc_attrs ++ &[_]std.builtin.Type.Struct.FieldAttributes{.{ .@"align" = result.alloc_align }}; - } else { - assert(result.alloc_align == null); - } - - assert(@alignOf(Descriptors) == 1); - - // Collect handler types, names, and drivers, to later be bound to the appropriate - // endpoints - const info = @typeInfo(Descriptors).@"struct"; - for (info.field_names, info.field_types, 0..) |field_name, field_type, desc_num| { - const desc = @field(descriptors, field_name); - - // Determine which interface numbers this driver owns. If it is an - // InterfaceAssociation, then use the interface count. If it is an Interface, - // then the driver owns just that one interface. - if (desc_num == 0) { - const itf_start, const itf_count = switch (field_type) { - descriptor.InterfaceAssociation => .{ desc.first_interface, desc.interface_count }, - descriptor.Interface => .{ desc.interface_number, 1 }, - else => |T| @compileError( - "Expected first descriptor of driver " ++ - @typeName(DriverType) ++ - " to be of type Interface or InterfaceAssociation descriptor, got: " ++ - @typeName(T), - ), - }; - if (itf_start != handlers_itf.len) - @compileError("interface numbering mismatch"); - - handlers_itf = handlers_itf ++ @as([itf_count]DriverName, @splat(driver_field_name)); - } - - switch (field_type) { - // Register handler for endpoints - descriptor.Endpoint => { - const ep_dir = @backingInt(desc.endpoint.dir); - const ep_num = @backingInt(desc.endpoint.num); - - if (ep_handler_types[ep_dir][ep_num] != void) - @compileError(std.fmt.comptimePrint( - "ep{} {t}: multiple handlers: {s} and {s}", - .{ ep_num, desc.endpoint.dir, ep_handler_drivers[ep_dir][ep_num], driver_field_name }, - )); - - ep_handler_types[ep_dir][ep_num] = EndpointHandler(runtime_field_types[drv_id]); - ep_handler_drivers[ep_dir][ep_num] = drv_id; - ep_handler_names[ep_dir][ep_num] = field_name; - }, - // Interface association must be first - descriptor.InterfaceAssociation => assert(desc_num == 0), - else => {}, - } - } - desc_field_types[drv_id] = Descriptors; - field_attrs[drv_id] = .{ .default_value_ptr = &descriptors }; - } - - // Finally, bind the handler functions based on the data collected above. - // Create a tuple with the appropriate types - const ep_handlers_types: [2]type = .{ @Tuple(&ep_handler_types[0]), @Tuple(&ep_handler_types[1]) }; - var ep_handlers: @Tuple(&ep_handlers_types) = undefined; - // Iterate over all IN and OUT endpoints and bind the handler for any that are set. - for (&ep_handler_types, &ep_handler_names, &ep_handler_drivers, 0..) |htypes, hnames, hdrivers, dir| { - for (&htypes, &hnames, &hdrivers, 0..) |T, name, drv_id, ep| { - if (T != void) - ep_handlers[dir][ep] = @field(runtime_field_types[drv_id.?].handlers, name); - } - } - - // alloc is invalidated after this point. It will cause a compile error if accessed. - const const_alloc = alloc.to_const(); - const const_ep_handlers = ep_handlers; - - const DriverConfig = @Struct( - .@"extern", - null, - driver_field_names, - &desc_field_types, - &field_attrs, - ); - - const Descriptor = extern struct { - first: descriptor.Configuration = .{ - .total_length = .from(@sizeOf(descriptor.Configuration) + @sizeOf(DriverConfig)), - .num_interfaces = const_alloc.next_itf_num, - .configuration_value = 1, - .configuration_s = configuration_s, - .attributes = options.attributes, - .max_current = .from_ma(options.max_current_ma), - }, - drv: DriverConfig = .{}, - }; - - std.testing.expectEqual( - (Descriptor{}).first.total_length.native(), - @sizeOf(Descriptor), - ) catch unreachable; - - const idx_in = @backingInt(types.Dir.in); - const idx_out = @backingInt(types.Dir.out); - return .{ - .{ - .Descriptor = Descriptor, - .DriverAlloc = @Struct( - .auto, - null, - driver_alloc_names, - driver_alloc_types[0..driver_alloc_attrs.len], - driver_alloc_attrs[0..driver_alloc_attrs.len], - ), - .drivers_ep = blk: { - var ret: @FieldType(@This(), "drivers_ep") = undefined; - for (&ret, ep_handler_drivers) |*dstv, srcv| { - for (dstv, srcv) |*dst, src_opt| { - dst.* = if (src_opt) |src| driver_field_names[src] else null; - } - } - break :blk ret; - }, - .HandlersEp = struct { - in: ep_handlers_types[idx_in] = const_ep_handlers[idx_in], - out: ep_handlers_types[idx_out] = const_ep_handlers[idx_out], - }, - .handlers_itf = handlers_itf, - .RuntimeData = @Struct( - .auto, - null, - driver_field_names, - &runtime_field_types, - &@splat(.{}), - ), - }, - const_alloc.strings, - }; - } - - pub fn init(comptime self: @This(), device_itf: *DeviceInterface, driver_data: *self.RuntimeData, driver_alloc: anytype, comptime config_descriptor: anytype) void { - inline for (@typeInfo(self.RuntimeData).@"struct".field_names) |driver_field_name| { - const cfg = @field(config_descriptor.drv, driver_field_name); - const desc_info = @typeInfo(@TypeOf(cfg)).@"struct"; - - // Open OUT endpoint first so that the driver can call ep_listen in init - inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { - const desc = &@field(cfg, field_name); - if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .out) - device_itf.ep_open(desc); - } - - const drv = &@field(driver_data, driver_field_name); - // Don't pass empty slices around - if (@hasField(@TypeOf(driver_alloc.*), driver_field_name)) - drv.init(&cfg, device_itf, &@field(driver_alloc, driver_field_name)) - else - drv.init(&cfg, device_itf); - - // Open IN endpoint last so that callbacks can happen - inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { - const desc = &@field(cfg, field_name); - if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .in) - device_itf.ep_open(desc); - } - } - } - - pub fn deinit(comptime self: @This(), device_itf: *DeviceInterface, driver_data: *self.RuntimeData) void { - _ = device_itf; - _ = driver_data; - // deinitialize drivers - } - }; -} - pub fn validate_controller(T: type) void { comptime { const info = @typeInfo(T); diff --git a/core/src/core/usb/configuration.zig b/core/src/core/usb/configuration.zig new file mode 100644 index 000000000..e9ac8421d --- /dev/null +++ b/core/src/core/usb/configuration.zig @@ -0,0 +1,259 @@ +const std = @import("std"); +const usb = @import("../usb.zig"); + +const assert = std.debug.assert; +const descriptor = usb.descriptor; +const types = usb.types; + +pub const Options = struct { + attributes: descriptor.Configuration.Attributes, + max_current_ma: u9, + name: []const u8 = "", + /// Only use either IN or OUT on each endpoint. Useful for debugging. + /// Realistically, it should only be turned off if you are exhausting + /// the 15 endpoint limit. + unique_endpoints: bool = true, +}; + +pub fn Create( + options: Options, + driver_config: anytype, + // driver_args: blk: { + // const info = @typeInfo(Drivers).@"struct"; + // const count = info.field_names.len; + // var field_names: [count][:0]const u8 = undefined; + // var field_types: [count]type = undefined; + // for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { + // // Collect field names + // field_names[i] = field_name; + // // Collect the type info for the Descriptor.create function parameter + // const param_types = @typeInfo(@TypeOf(field_type.Descriptor.create)).@"fn".param_types; + // // Ensure it takes 3 parameters + // assert(param_types.len == 3); + // // The first must be a DescriptorAllocator + // assert(param_types[0] == *DescriptorAllocator); + // // The second is usb.types.PacketLength + // assert(param_types[1] == types.PacketLength); + // // And save the type of the third + // assert(param_types[2] == field_type); + // field_types[i] = param_types[2].?; + // } + // break :blk @Struct(.auto, null, &field_names, &field_types, &@splat(.{})); + // }, +) type { + return struct { + const DriverName = []const u8; + + Descriptor: type, + DriverAlloc: type, + drivers_ep: [2][16]?DriverName, + HandlersEp: type, + handlers_itf: []const DriverName, + RuntimeData: type, + + pub fn create(max_psize: types.PacketLength, strings: []const []const u8) struct { @This(), []const []const u8 } { + var alloc = usb.DescriptorAllocator.init(options.unique_endpoints, strings); + const configuration_s = alloc.string(options.name); + const driver_info = @typeInfo(@TypeOf(driver_config)).@"struct"; + const driver_field_names = driver_info.field_names; + + var desc_field_types: [driver_field_names.len]type = undefined; + var runtime_field_types: [driver_field_names.len]type = undefined; + var field_attrs: [driver_field_names.len]std.builtin.Type.Struct.FieldAttributes = undefined; + var ep_handler_types: [2][16]type = @splat(@splat(void)); + var ep_handler_names: [2][16][:0]const u8 = undefined; + var ep_handler_drivers: [2][16]?usize = @splat(@splat(null)); + var handlers_itf: []const DriverName = &.{}; + var driver_alloc_names: []const [:0]const u8 = &.{}; + var driver_alloc_types: []const type = &.{}; + var driver_alloc_attrs: []const std.builtin.Type.Struct.FieldAttributes = &.{}; + + for (driver_field_names, driver_info.field_types, 0..) |driver_field_name, DriverType, drv_id| { + runtime_field_types[drv_id] = if (@hasField(DriverType, "generic_runtime")) + DriverType.Runtime(@field(driver_config, driver_field_name).generic_runtime) + else + DriverType.Runtime; + + // Get descriptor type for the current driver + const Descriptors = DriverType.Descriptor; + // Call the create method on the descriptor, which wraps it with the allow stuff. + const result = Descriptors.create(&alloc, max_psize, @field(driver_config, driver_field_name)); + // Get the descriptor instance from the result. + const descriptors = result.descriptor; + + // If the driver requests memory, then collect the names, types, and attrs + if (result.alloc_bytes) |len| { + driver_alloc_names = driver_alloc_names ++ &[_][:0]const u8{driver_field_name}; + driver_alloc_types = driver_alloc_types ++ &[_]type{[len]u8}; + driver_alloc_attrs = driver_alloc_attrs ++ &[_]std.builtin.Type.Struct.FieldAttributes{.{ .@"align" = result.alloc_align }}; + } else { + assert(result.alloc_align == null); + } + + assert(@alignOf(Descriptors) == 1); + + // Collect handler types, names, and drivers, to later be bound to the appropriate + // endpoints + const info = @typeInfo(Descriptors).@"struct"; + for (info.field_names, info.field_types, 0..) |field_name, field_type, desc_num| { + const desc = @field(descriptors, field_name); + + // Determine which interface numbers this driver owns. If it is an + // InterfaceAssociation, then use the interface count. If it is an Interface, + // then the driver owns just that one interface. + if (desc_num == 0) { + const itf_start, const itf_count = switch (field_type) { + descriptor.InterfaceAssociation => .{ desc.first_interface, desc.interface_count }, + descriptor.Interface => .{ desc.interface_number, 1 }, + else => |T| @compileError( + "Expected first descriptor of driver " ++ + @typeName(DriverType) ++ + " to be of type Interface or InterfaceAssociation descriptor, got: " ++ + @typeName(T), + ), + }; + if (itf_start != handlers_itf.len) + @compileError("interface numbering mismatch"); + + handlers_itf = handlers_itf ++ @as([itf_count]DriverName, @splat(driver_field_name)); + } + + switch (field_type) { + // Register handler for endpoints + descriptor.Endpoint => { + const ep_dir = @backingInt(desc.endpoint.dir); + const ep_num = @backingInt(desc.endpoint.num); + + if (ep_handler_types[ep_dir][ep_num] != void) + @compileError(std.fmt.comptimePrint( + "ep{} {t}: multiple handlers: {s} and {s}", + .{ ep_num, desc.endpoint.dir, ep_handler_drivers[ep_dir][ep_num], driver_field_name }, + )); + + ep_handler_types[ep_dir][ep_num] = usb.EndpointHandler(runtime_field_types[drv_id]); + ep_handler_drivers[ep_dir][ep_num] = drv_id; + ep_handler_names[ep_dir][ep_num] = field_name; + }, + // Interface association must be first + descriptor.InterfaceAssociation => assert(desc_num == 0), + else => {}, + } + } + desc_field_types[drv_id] = Descriptors; + field_attrs[drv_id] = .{ .default_value_ptr = &descriptors }; + } + + // Finally, bind the handler functions based on the data collected above. + // Create a tuple with the appropriate types + const ep_handlers_types: [2]type = .{ @Tuple(&ep_handler_types[0]), @Tuple(&ep_handler_types[1]) }; + var ep_handlers: @Tuple(&ep_handlers_types) = undefined; + // Iterate over all IN and OUT endpoints and bind the handler for any that are set. + for (&ep_handler_types, &ep_handler_names, &ep_handler_drivers, 0..) |htypes, hnames, hdrivers, dir| { + for (&htypes, &hnames, &hdrivers, 0..) |T, name, drv_id, ep| { + if (T != void) + ep_handlers[dir][ep] = @field(runtime_field_types[drv_id.?].handlers, name); + } + } + + // alloc is invalidated after this point. It will cause a compile error if accessed. + const const_alloc = alloc.to_const(); + const const_ep_handlers = ep_handlers; + + const DriverConfig = @Struct( + .@"extern", + null, + driver_field_names, + &desc_field_types, + &field_attrs, + ); + + const Descriptor = extern struct { + first: descriptor.Configuration = .{ + .total_length = .from(@sizeOf(descriptor.Configuration) + @sizeOf(DriverConfig)), + .num_interfaces = const_alloc.next_itf_num, + .configuration_value = 1, + .configuration_s = configuration_s, + .attributes = options.attributes, + .max_current = .from_ma(options.max_current_ma), + }, + drv: DriverConfig = .{}, + }; + + std.testing.expectEqual( + (Descriptor{}).first.total_length.native(), + @sizeOf(Descriptor), + ) catch unreachable; + + const idx_in = @backingInt(types.Dir.in); + const idx_out = @backingInt(types.Dir.out); + return .{ + .{ + .Descriptor = Descriptor, + .DriverAlloc = @Struct( + .auto, + null, + driver_alloc_names, + driver_alloc_types[0..driver_alloc_attrs.len], + driver_alloc_attrs[0..driver_alloc_attrs.len], + ), + .drivers_ep = blk: { + var ret: @FieldType(@This(), "drivers_ep") = undefined; + for (&ret, ep_handler_drivers) |*dstv, srcv| { + for (dstv, srcv) |*dst, src_opt| { + dst.* = if (src_opt) |src| driver_field_names[src] else null; + } + } + break :blk ret; + }, + .HandlersEp = struct { + in: ep_handlers_types[idx_in] = const_ep_handlers[idx_in], + out: ep_handlers_types[idx_out] = const_ep_handlers[idx_out], + }, + .handlers_itf = handlers_itf, + .RuntimeData = @Struct( + .auto, + null, + driver_field_names, + &runtime_field_types, + &@splat(.{}), + ), + }, + const_alloc.strings, + }; + } + + pub fn init(comptime self: @This(), device_itf: *usb.DeviceInterface, driver_data: *self.RuntimeData, driver_alloc: anytype, comptime config_descriptor: anytype) void { + inline for (@typeInfo(self.RuntimeData).@"struct".field_names) |driver_field_name| { + const cfg = @field(config_descriptor.drv, driver_field_name); + const desc_info = @typeInfo(@TypeOf(cfg)).@"struct"; + + // Open OUT endpoint first so that the driver can call ep_listen in init + inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { + const desc = &@field(cfg, field_name); + if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .out) + device_itf.ep_open(desc); + } + + const drv = &@field(driver_data, driver_field_name); + // Don't pass empty slices around + if (@hasField(@TypeOf(driver_alloc.*), driver_field_name)) + drv.init(&cfg, device_itf, &@field(driver_alloc, driver_field_name)) + else + drv.init(&cfg, device_itf); + + // Open IN endpoint last so that callbacks can happen + inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { + const desc = &@field(cfg, field_name); + if (comptime field_type == descriptor.Endpoint and desc.endpoint.dir == .in) + device_itf.ep_open(desc); + } + } + } + + pub fn deinit(comptime self: @This(), device_itf: *usb.DeviceInterface, driver_data: *self.RuntimeData) void { + _ = device_itf; + _ = driver_data; + // deinitialize drivers + } + }; +} diff --git a/examples/nordic/nrf5x/src/usb_cdc.zig b/examples/nordic/nrf5x/src/usb_cdc.zig index 0b103e4f9..0f23be203 100644 --- a/examples/nordic/nrf5x/src/usb_cdc.zig +++ b/examples/nordic/nrf5x/src/usb_cdc.zig @@ -38,7 +38,7 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = USBD.max_supported_packet_size, -}, &.{usb.Configuration( +}, &.{usb.configuration.Create( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ .serial = usb.drivers.CDC{ .itf_notifi_str = "Board CDC", .itf_data_str = "Board CDC Data" } }, )}) = .init; diff --git a/examples/nordic/nrf5x/src/usb_hid.zig b/examples/nordic/nrf5x/src/usb_hid.zig index 2d386d981..b993bf88f 100644 --- a/examples/nordic/nrf5x/src/usb_hid.zig +++ b/examples/nordic/nrf5x/src/usb_hid.zig @@ -139,7 +139,7 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = USBD.max_supported_packet_size, -}, &.{usb.Configuration( +}, &.{usb.configuration.Create( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ .keyboard = hid_driver_options }, )}) = .init; diff --git a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig index bb7ce9eec..c9d354861 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig @@ -21,7 +21,7 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = USB_Device.max_supported_packet_size, -}, &.{usb.Configuration( +}, &.{usb.configuration.Create( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ .serial = usb.drivers.CDC{ .itf_notifi_str = "Board CDC", .itf_data_str = "Board CDC Data" }, diff --git a/examples/raspberrypi/rp2xxx/src/usb_hid.zig b/examples/raspberrypi/rp2xxx/src/usb_hid.zig index b6c987211..cf12f912e 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_hid.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_hid.zig @@ -132,7 +132,7 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = USB_Device.max_supported_packet_size, -}, &.{usb.Configuration( +}, &.{usb.configuration.Create( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ .keyboard = hid_driver_options, diff --git a/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig b/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig index eeaecaf3e..3d70250b7 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig @@ -20,7 +20,7 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = USB_Device.max_supported_packet_size, -}, &.{usb.Configuration( +}, &.{usb.configuration.Create( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ .echo = usb.drivers.EchoExample{}, diff --git a/examples/wch/ch32v/src/usb_cdc.zig b/examples/wch/ch32v/src/usb_cdc.zig index b50d7ec8e..4feb73a27 100644 --- a/examples/wch/ch32v/src/usb_cdc.zig +++ b/examples/wch/ch32v/src/usb_cdc.zig @@ -31,7 +31,7 @@ const USB_Controller = usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .max_supported_packet_size = hal.usb.max_packet_size, -}, &.{usb.Configuration( +}, &.{usb.configuration.Create( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ .serial = usb.drivers.CDC{ .itf_notifi_str = "Board CDC", .itf_data_str = "Board CDC Data" } }, )}); From b2dc27b7a00b657bb6270c2c5eef1b35faebf2fd Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Wed, 11 Nov 2026 04:36:26 +0100 Subject: [PATCH 13/28] Allow more freedom with descriptor and runtime generics --- core/src/core/usb.zig | 2 + core/src/core/usb/configuration.zig | 34 ++-- core/src/core/usb/drivers/CDC.zig | 208 ++++++++++---------- core/src/core/usb/drivers/EchoExample.zig | 100 +++++----- core/src/core/usb/drivers/HID.zig | 148 +++++++------- examples/nordic/nrf5x/src/usb_hid.zig | 80 ++++---- examples/raspberrypi/rp2xxx/src/usb_hid.zig | 80 ++++---- port/nxp/mcx/build.zig.zon | 10 +- port/raspberrypi/rp2xxx/src/hal/usb.zig | 56 +++--- 9 files changed, 368 insertions(+), 350 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index b913c6502..7b89bce02 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -59,6 +59,8 @@ pub const DescriptorAllocator = struct { /// Wraps a Descriptor type. Returned by the `create` method of the Descriptor. pub fn DescriptorCreateResult(Descriptor: type) type { return struct { + const Inner = Descriptor; + descriptor: Descriptor, /// If not null, a slice of this length will be passed /// to driver's init function. diff --git a/core/src/core/usb/configuration.zig b/core/src/core/usb/configuration.zig index e9ac8421d..fece74c3f 100644 --- a/core/src/core/usb/configuration.zig +++ b/core/src/core/usb/configuration.zig @@ -69,19 +69,20 @@ pub fn Create( var driver_alloc_attrs: []const std.builtin.Type.Struct.FieldAttributes = &.{}; for (driver_field_names, driver_info.field_types, 0..) |driver_field_name, DriverType, drv_id| { - runtime_field_types[drv_id] = if (@hasField(DriverType, "generic_runtime")) - DriverType.Runtime(@field(driver_config, driver_field_name).generic_runtime) - else - DriverType.Runtime; + const drv = @field(driver_config, driver_field_name); // Get descriptor type for the current driver - const Descriptors = DriverType.Descriptor; // Call the create method on the descriptor, which wraps it with the allow stuff. - const result = Descriptors.create(&alloc, max_psize, @field(driver_config, driver_field_name)); - // Get the descriptor instance from the result. - const descriptors = result.descriptor; + const result = drv.create_descriptor(&alloc, max_psize); + const Descriptor = @TypeOf(result.descriptor); // If the driver requests memory, then collect the names, types, and attrs + const Runtime = switch (@typeInfo(@TypeOf(DriverType.Runtime))) { + .@"fn" => drv.Runtime(), + else => DriverType.Runtime, + }; + runtime_field_types[drv_id] = Runtime; + if (result.alloc_bytes) |len| { driver_alloc_names = driver_alloc_names ++ &[_][:0]const u8{driver_field_name}; driver_alloc_types = driver_alloc_types ++ &[_]type{[len]u8}; @@ -90,13 +91,13 @@ pub fn Create( assert(result.alloc_align == null); } - assert(@alignOf(Descriptors) == 1); + assert(@alignOf(Descriptor) == 1); // Collect handler types, names, and drivers, to later be bound to the appropriate // endpoints - const info = @typeInfo(Descriptors).@"struct"; + const info = @typeInfo(Descriptor).@"struct"; for (info.field_names, info.field_types, 0..) |field_name, field_type, desc_num| { - const desc = @field(descriptors, field_name); + const desc = @field(result.descriptor, field_name); // Determine which interface numbers this driver owns. If it is an // InterfaceAssociation, then use the interface count. If it is an Interface, @@ -139,8 +140,8 @@ pub fn Create( else => {}, } } - desc_field_types[drv_id] = Descriptors; - field_attrs[drv_id] = .{ .default_value_ptr = &descriptors }; + desc_field_types[drv_id] = Descriptor; + field_attrs[drv_id] = .{ .default_value_ptr = &result.descriptor }; } // Finally, bind the handler functions based on the data collected above. @@ -234,12 +235,13 @@ pub fn Create( device_itf.ep_open(desc); } - const drv = &@field(driver_data, driver_field_name); + const drv = @field(driver_config, driver_field_name); + const runtime = &@field(driver_data, driver_field_name); // Don't pass empty slices around if (@hasField(@TypeOf(driver_alloc.*), driver_field_name)) - drv.init(&cfg, device_itf, &@field(driver_alloc, driver_field_name)) + drv.init_runtime(cfg, runtime, device_itf, &@field(driver_alloc, driver_field_name)) else - drv.init(&cfg, device_itf); + drv.init_runtime(cfg, runtime, device_itf); // Open IN endpoint last so that callbacks can happen inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { diff --git a/core/src/core/usb/drivers/CDC.zig b/core/src/core/usb/drivers/CDC.zig index 1efbca24a..a6e4d75ce 100644 --- a/core/src/core/usb/drivers/CDC.zig +++ b/core/src/core/usb/drivers/CDC.zig @@ -55,11 +55,6 @@ pub const LineCoding = extern struct { }; }; -const CDC_Driver = @This(); - -itf_notifi_str: []const u8 = "", -itf_data_str: []const u8 = "", - // This struct bundles all the descriptors CDC needs into one Configuration. pub const Descriptor = extern struct { const desc = usb.descriptor; @@ -74,78 +69,6 @@ pub const Descriptor = extern struct { itf_data: desc.Interface, ep_out: desc.Endpoint, ep_in: desc.Endpoint, - - /// This function is used during descriptor creation. Endpoint and interface numbers are - /// allocated through the `alloc` parameter. Third argument can be of any type, it's passed - /// by the user when creating the device controller type. If multiple instances of a driver - /// are used, this function is called for each, with different arguments. Passing arguments - /// through this function is preferred to making the whole driver generic. - pub fn create( - alloc: *usb.DescriptorAllocator, - max_supported_packet_size: usb.types.PacketLength, - options: CDC_Driver, - ) usb.DescriptorCreateResult(@This()) { - // Endpoint and interface numbers are allocated through the `alloc` parameter, - // so that multiple instances of this driver can coexist. - const itf_notifi = alloc.next_itf(); - const itf_data = alloc.next_itf(); - return .{ - .descriptor = .{ - .itf_assoc = .{ - .first_interface = itf_notifi, - .interface_count = 2, - .function_class = 2, - .function_subclass = 2, - .function_protocol = 0, - .function = 0, - }, - .itf_notifi = .{ - .interface_number = itf_notifi, - .alternate_setting = 0, - .num_endpoints = 1, - .interface_triple = .from(.CDC, .Abstract, .NoneRequired), - .interface_s = alloc.string(options.itf_notifi_str), - }, - .cdc_header = .{ .bcd_cdc = .from(1, 20) }, - .cdc_call_mgmt = .{ - .capabilities = .none, - .data_interface = itf_data, - }, - .cdc_acm = .{ - .capabilities = .{ - .comm_feature = false, - .send_break = false, - // Line coding requests get sent regardless of this bit - .line_coding = true, - .network_connection = false, - }, - }, - .cdc_union = .{ - .master_interface = itf_notifi, - .slave_interface_0 = itf_data, - }, - // High-speed interrupt intervals are encoded as - // 2^(bInterval - 1) microframes, while full-speed intervals - // are expressed directly in milliseconds. Keep the intended - // polling period at 16 ms for both speeds. - .ep_notifi = .interrupt( - alloc.next_ep(.in), - 8, - if (max_supported_packet_size > 64) 8 else 16, - ), - .itf_data = .{ - .interface_number = itf_data, - .alternate_setting = 0, - .num_endpoints = 2, - .interface_triple = .from(.CDC_Data, .Unused, .NoneRequired), - .interface_s = alloc.string(options.itf_data_str), - }, - .ep_out = .bulk(alloc.next_ep(.out), max_supported_packet_size), - .ep_in = .bulk(alloc.next_ep(.in), max_supported_packet_size), - }, - .alloc_bytes = 2 * max_supported_packet_size, - }; - } }; pub const Runtime = struct { @@ -225,30 +148,6 @@ pub const Runtime = struct { .ep_in = on_tx_ready, }; - // Called when the host selects a configuration. - pub fn init(self: *@This(), desc: *const Descriptor, device: *usb.DeviceInterface, data: []u8) void { - const len_half = @divExact(data.len, 2); - assert(len_half == desc.ep_in.max_packet_size.native(), .{}); - assert(len_half == desc.ep_out.max_packet_size.native(), .{}); - self.* = .{ - .device = device, - .descriptor = desc, - .line_coding = .init, - .notifi_ready = .init(true), - - // `init` provides a data buffer, which we split in half for rx and tx data. - .rx_data = data[0..len_half], - .rx_seek = 0, - .rx_end = 0, - .rx_ready = .init(false), - - .tx_data = data[len_half..], - .tx_end = 0, - .tx_ready = .init(true), - }; - device.ep_listen(desc.ep_out.endpoint.num, @intCast(self.rx_data.len)); - } - /// Handle class-specific SETUP requests where recipient=Interface /// Called by DeviceController when the interface number matches this driver. pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { @@ -282,3 +181,110 @@ pub const Runtime = struct { self.notifi_ready.store(true, .seq_cst); } }; + +const CDC_Driver = @This(); + +itf_notifi_str: []const u8 = "", +itf_data_str: []const u8 = "", + +/// This function is used during descriptor creation. Endpoint and interface numbers are +/// allocated through the `alloc` parameter. Third argument can be of any type, it's passed +/// by the user when creating the device controller type. If multiple instances of a driver +/// are used, this function is called for each, with different arguments. Passing arguments +/// through this function is preferred to making the whole driver generic. +pub fn create_descriptor( + comptime self: @This(), + alloc: *usb.DescriptorAllocator, + max_supported_packet_size: usb.types.PacketLength, +) usb.DescriptorCreateResult(Descriptor) { + // Endpoint and interface numbers are allocated through the `alloc` parameter, + // so that multiple instances of this driver can coexist. + const itf_notifi = alloc.next_itf(); + const itf_data = alloc.next_itf(); + return .{ + .descriptor = .{ + .itf_assoc = .{ + .first_interface = itf_notifi, + .interface_count = 2, + .function_class = 2, + .function_subclass = 2, + .function_protocol = 0, + .function = 0, + }, + .itf_notifi = .{ + .interface_number = itf_notifi, + .alternate_setting = 0, + .num_endpoints = 1, + .interface_triple = .from(.CDC, .Abstract, .NoneRequired), + .interface_s = alloc.string(self.itf_notifi_str), + }, + .cdc_header = .{ .bcd_cdc = .from(1, 20) }, + .cdc_call_mgmt = .{ + .capabilities = .none, + .data_interface = itf_data, + }, + .cdc_acm = .{ + .capabilities = .{ + .comm_feature = false, + .send_break = false, + // Line coding requests get sent regardless of this bit + .line_coding = true, + .network_connection = false, + }, + }, + .cdc_union = .{ + .master_interface = itf_notifi, + .slave_interface_0 = itf_data, + }, + // High-speed interrupt intervals are encoded as + // 2^(bInterval - 1) microframes, while full-speed intervals + // are expressed directly in milliseconds. Keep the intended + // polling period at 16 ms for both speeds. + .ep_notifi = .interrupt( + alloc.next_ep(.in), + 8, + if (max_supported_packet_size > 64) 8 else 16, + ), + .itf_data = .{ + .interface_number = itf_data, + .alternate_setting = 0, + .num_endpoints = 2, + .interface_triple = .from(.CDC_Data, .Unused, .NoneRequired), + .interface_s = alloc.string(self.itf_data_str), + }, + .ep_out = .bulk(alloc.next_ep(.out), max_supported_packet_size), + .ep_in = .bulk(alloc.next_ep(.in), max_supported_packet_size), + }, + .alloc_bytes = 2 * max_supported_packet_size, + }; +} + +// Called when the host selects a configuration. +pub fn init_runtime( + comptime _: @This(), + comptime descriptor: Descriptor, + runtime: *Runtime, + device: *usb.DeviceInterface, + data: []u8, +) void { + const len_half = @divExact(data.len, 2); + assert(len_half == descriptor.ep_in.max_packet_size.native(), .{}); + assert(len_half == descriptor.ep_out.max_packet_size.native(), .{}); + runtime.* = .{ + .device = device, + .descriptor = &descriptor, + .line_coding = .init, + .notifi_ready = .init(true), + + // `init` provides a data buffer, which we split in half for rx and tx data. + .rx_data = data[0..len_half], + .rx_seek = 0, + .rx_end = 0, + .rx_ready = .init(false), + + .tx_data = data[len_half..], + .tx_end = 0, + .tx_ready = .init(true), + }; + device.ep_listen(descriptor.ep_out.endpoint.num, @intCast(runtime.rx_data.len)); +} diff --git a/core/src/core/usb/drivers/EchoExample.zig b/core/src/core/usb/drivers/EchoExample.zig index 508987ecd..5eafe117f 100644 --- a/core/src/core/usb/drivers/EchoExample.zig +++ b/core/src/core/usb/drivers/EchoExample.zig @@ -4,10 +4,6 @@ const usb = @import("../../usb.zig"); const assert = std.debug.assert; const log = std.log.scoped(.usb_echo); -pub const EchoExampleDriver = @This(); - -itf_string: []const u8 = "", - /// The descriptors need to have the same memory layout as the sent data. pub const Descriptor = extern struct { const desc = usb.descriptor; @@ -15,33 +11,6 @@ pub const Descriptor = extern struct { itf: desc.Interface, ep_out: desc.Endpoint, ep_in: desc.Endpoint, - - /// This function is used during descriptor creation. Endpoint and interface numbers are - /// allocated through the `alloc` parameter. Third argument contains driver configuration. - /// If multiple instances of a driver are used, this function is called for each, - /// with different arguments. - pub fn create( - alloc: *usb.DescriptorAllocator, - max_supported_packet_size: usb.types.PacketLength, - options: EchoExampleDriver, - ) usb.DescriptorCreateResult(@This()) { - return .{ - .descriptor = .{ - .itf = .{ - .interface_number = alloc.next_itf(), - .alternate_setting = 0, - .num_endpoints = 2, - .interface_triple = .vendor_specific, - .interface_s = alloc.string(options.itf_string), - }, - .ep_out = .bulk(alloc.next_ep(.out), max_supported_packet_size), - .ep_in = .bulk(alloc.next_ep(.in), max_supported_packet_size), - }, - // Buffers whose length is only known after creating the - // descriptor can be allocated at this stage. - .alloc_bytes = max_supported_packet_size, - }; - } }; pub const Runtime = struct { @@ -58,22 +27,6 @@ pub const Runtime = struct { packet_buffer: []u8, tx_ready: std.atomic.Value(bool), - /// This function is called when the host chooses a configuration that contains this driver. `self` - /// points to undefined memory. `data` is of the length specified in `Descriptor.create()`. - pub fn init(self: *@This(), desc: *const Descriptor, device: *usb.DeviceInterface, data: []u8) void { - assert(data.len == desc.ep_in.max_packet_size.native()); - self.* = .{ - .device = device, - .descriptor = desc, - .packet_buffer = data, - .tx_ready = .init(false), - }; - device.ep_listen( - desc.ep_out.endpoint.num, - @intCast(desc.ep_out.max_packet_size.native()), - ); - } - /// Used for interface configuration through endpoint 0. /// Data returned by this function is sent on endpoint 0. pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { @@ -116,3 +69,56 @@ pub const Runtime = struct { self.device.ep_listen(ep_rx, 64); } }; + +pub const EchoExampleDriver = @This(); + +itf_string: []const u8 = "", + +/// This function is used during descriptor creation. Endpoint and interface numbers are +/// allocated through the `alloc` parameter. Third argument contains driver configuration. +/// If multiple instances of a driver are used, this function is called for each, +/// with different arguments. +pub fn create_descriptor( + self: @This(), + alloc: *usb.DescriptorAllocator, + max_supported_packet_size: usb.types.PacketLength, +) usb.DescriptorCreateResult(Descriptor) { + return .{ + .descriptor = .{ + .itf = .{ + .interface_number = alloc.next_itf(), + .alternate_setting = 0, + .num_endpoints = 2, + .interface_triple = .vendor_specific, + .interface_s = alloc.string(self.itf_string), + }, + .ep_out = .bulk(alloc.next_ep(.out), max_supported_packet_size), + .ep_in = .bulk(alloc.next_ep(.in), max_supported_packet_size), + }, + // Buffers whose length is only known after creating the + // descriptor can be allocated at this stage. + .alloc_bytes = max_supported_packet_size, + }; +} + +/// This function is called when the host chooses a configuration that contains this driver. `self` +/// points to undefined memory. `data` is of the length specified in `Descriptor.create()`. +pub fn init_runtime( + comptime _: @This(), + comptime desc: Descriptor, + runtime: *Runtime, + device: *usb.DeviceInterface, + data: []u8, +) void { + assert(data.len == desc.ep_in.max_packet_size.native()); + runtime.* = .{ + .device = device, + .descriptor = &desc, + .packet_buffer = data, + .tx_ready = .init(false), + }; + device.ep_listen( + desc.ep_out.endpoint.num, + @intCast(desc.ep_out.max_packet_size.native()), + ); +} diff --git a/core/src/core/usb/drivers/HID.zig b/core/src/core/usb/drivers/HID.zig index 559d8e87b..ef853ddfc 100644 --- a/core/src/core/usb/drivers/HID.zig +++ b/core/src/core/usb/drivers/HID.zig @@ -1,6 +1,7 @@ const std = @import("std"); const usb = @import("../../usb.zig"); const assert = std.debug.assert; +const log = std.log.scoped(.usb_hid_int_driver); /// Reports are a list of tagged ?i32 values. Encoding is variable-length. pub const ReportItem = union(enum) { @@ -291,23 +292,6 @@ pub const ReportItem = union(enum) { } }; -const ClassCode = usb.types.ClassSubclassProtocol.ClassCode.HID; - -pub const HID_InterruptDriver = @This(); - -subclass: ClassCode.Subclass(), -protocol: ClassCode.Protocol(), - -itf_string: []const u8 = "", -poll_interval: u8, -country_code: usb.descriptor.HID.CountryCode = .NotSupported, - -generic_runtime: struct { - report_descriptor: []const ?ReportItem, - InReport: type, - OutReport: type, -}, - pub const Descriptor = extern struct { const desc = usb.descriptor; @@ -315,45 +299,10 @@ pub const Descriptor = extern struct { hid: desc.HID, ep_out: desc.Endpoint, ep_in: desc.Endpoint, - - pub fn create( - alloc: *usb.DescriptorAllocator, - max_supported_packet_size: usb.types.PacketLength, - options: HID_InterruptDriver, - ) usb.DescriptorCreateResult(@This()) { - assert(@sizeOf(options.generic_runtime.InReport) <= max_supported_packet_size); - assert(@sizeOf(options.generic_runtime.OutReport) <= max_supported_packet_size); - return .{ .descriptor = .{ - .interface = .{ - .interface_number = alloc.next_itf(), - .alternate_setting = 0, - .num_endpoints = 2, - .interface_triple = .from(.HID, options.subclass, options.protocol), - .interface_s = alloc.string(options.itf_string), - }, - .hid = .{ - .country_code = options.country_code, - .num_descriptors = 1, - .report_length = .from(options.generic_runtime.report_descriptor.len), - }, - .ep_out = .interrupt( - alloc.next_ep(.out), - @sizeOf(options.generic_runtime.OutReport), - options.poll_interval, - ), - .ep_in = .interrupt( - alloc.next_ep(.in), - @sizeOf(options.generic_runtime.InReport), - options.poll_interval, - ), - } }; - } }; /// HID Driver with an IN and OUT endpoint -pub fn Runtime(options: @FieldType(HID_InterruptDriver, "generic_runtime")) type { - const log = std.log.scoped(.usb_hid_int_driver); - +pub fn RuntimeGeneric(InReport: type, OutReport: type, report_descriptor: []const u8) type { return struct { pub const RequestType = enum(u8) { GetReport = 0x01, @@ -365,11 +314,6 @@ pub fn Runtime(options: @FieldType(HID_InterruptDriver, "generic_runtime")) type _, }; - pub const report_descriptor = ReportItem.create_report(options.report_descriptor); - - const OutReport = options.OutReport; - const InReport = options.InReport; - pub const Descriptor = HID_InterruptDriver.Descriptor; pub const handlers: usb.DriverHandlers(HID_InterruptDriver, @This()) = .{ @@ -382,20 +326,6 @@ pub fn Runtime(options: @FieldType(HID_InterruptDriver, "generic_runtime")) type tx_ready: std.atomic.Value(bool), rx_ready: std.atomic.Value(bool), - pub fn init(self: *@This(), desc: *const @This().Descriptor, device: *usb.DeviceInterface) void { - log.debug("init", .{}); - self.* = .{ - .device = device, - .descriptor = desc, - .tx_ready = .init(true), - .rx_ready = .init(false), - }; - self.device.ep_listen( - self.descriptor.ep_out.endpoint.num, - @intCast(self.descriptor.ep_out.max_packet_size.native()), - ); - } - pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { log.debug("class_request {any}", .{setup}); switch (setup.request_type.type) { @@ -491,3 +421,77 @@ pub fn Runtime(options: @FieldType(HID_InterruptDriver, "generic_runtime")) type } }; } + +pub fn Runtime(self: @This()) type { + return RuntimeGeneric( + self.InReport, + self.OutReport, + ReportItem.create_report(self.report_descriptor), + ); +} + +const ClassCode = usb.types.ClassSubclassProtocol.ClassCode.HID; + +pub const HID_InterruptDriver = @This(); + +subclass: ClassCode.Subclass(), +protocol: ClassCode.Protocol(), + +itf_string: []const u8 = "", +poll_interval: u8, +country_code: usb.descriptor.HID.CountryCode = .NotSupported, +report_descriptor: []const ?ReportItem, +InReport: type, +OutReport: type, + +pub fn create_descriptor( + comptime self: @This(), + alloc: *usb.DescriptorAllocator, + max_supported_packet_size: usb.types.PacketLength, +) usb.DescriptorCreateResult(Descriptor) { + assert(@sizeOf(self.InReport) <= max_supported_packet_size); + assert(@sizeOf(self.OutReport) <= max_supported_packet_size); + return .{ .descriptor = .{ + .interface = .{ + .interface_number = alloc.next_itf(), + .alternate_setting = 0, + .num_endpoints = 2, + .interface_triple = .from(.HID, self.subclass, self.protocol), + .interface_s = alloc.string(self.itf_string), + }, + .hid = .{ + .country_code = self.country_code, + .num_descriptors = 1, + .report_length = .from(self.report_descriptor.len), + }, + .ep_out = .interrupt( + alloc.next_ep(.out), + @sizeOf(self.OutReport), + self.poll_interval, + ), + .ep_in = .interrupt( + alloc.next_ep(.in), + @sizeOf(self.InReport), + self.poll_interval, + ), + } }; +} + +pub fn init_runtime( + comptime self: @This(), + comptime descriptor: Descriptor, + runtime: *self.Runtime(), + device: *usb.DeviceInterface, +) void { + log.debug("init", .{}); + runtime.* = .{ + .device = device, + .descriptor = &descriptor, + .tx_ready = .init(true), + .rx_ready = .init(false), + }; + device.ep_listen( + descriptor.ep_out.endpoint.num, + @intCast(descriptor.ep_out.max_packet_size.native()), + ); +} diff --git a/examples/nordic/nrf5x/src/usb_hid.zig b/examples/nordic/nrf5x/src/usb_hid.zig index b993bf88f..a4aadbb6c 100644 --- a/examples/nordic/nrf5x/src/usb_hid.zig +++ b/examples/nordic/nrf5x/src/usb_hid.zig @@ -85,48 +85,46 @@ const hid_driver_options: usb.drivers.HID_Interrupt = .{ .protocol = .Boot, .itf_string = "Boot Keyboard", .poll_interval = 1, - .generic_runtime = .{ - .report_descriptor = &.{ - .{ .global_usage_page = .generic_desktop }, - .local_usage_enum(.{ .generic_desktop = .keyboard }), - .{ .main_collection = .Application }, - // Input: modifier key bitmap - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0xE0, 0xE7 }, - .count = 8, - .Child = bool, - .dir = .in, - .type = .dynamic, - } }, - // Reserved 8 bits - .{ .data_static = .{ .in, u8 } }, - // Output: indicator LEDs - .{ .data = .{ - .usage = .{ .global_page = .led }, - .usage_range = .{ 1, 5 }, - .count = 5, - .Child = bool, - .dir = .out, - .type = .dynamic, - } }, - // Padding - .{ .data_static = .{ .out, u3 } }, - // Input: up to 6 pressed key codes - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0x00, 0xff }, - .count = 6, - .Child = u8, - .dir = .in, - .type = .selector, - } }, - // End - .main_collection_end, - }, - .InReport = KeyboardInReport, - .OutReport = KeyboardOutReport, + .report_descriptor = &.{ + .{ .global_usage_page = .generic_desktop }, + .local_usage_enum(.{ .generic_desktop = .keyboard }), + .{ .main_collection = .Application }, + // Input: modifier key bitmap + .{ .data = .{ + .usage = .{ .global_page = .keyboard }, + .usage_range = .{ 0xE0, 0xE7 }, + .count = 8, + .Child = bool, + .dir = .in, + .type = .dynamic, + } }, + // Reserved 8 bits + .{ .data_static = .{ .in, u8 } }, + // Output: indicator LEDs + .{ .data = .{ + .usage = .{ .global_page = .led }, + .usage_range = .{ 1, 5 }, + .count = 5, + .Child = bool, + .dir = .out, + .type = .dynamic, + } }, + // Padding + .{ .data_static = .{ .out, u3 } }, + // Input: up to 6 pressed key codes + .{ .data = .{ + .usage = .{ .global_page = .keyboard }, + .usage_range = .{ 0x00, 0xff }, + .count = 6, + .Child = u8, + .dir = .in, + .type = .selector, + } }, + // End + .main_collection_end, }, + .InReport = KeyboardInReport, + .OutReport = KeyboardOutReport, }; var usb_device: USBD = undefined; diff --git a/examples/raspberrypi/rp2xxx/src/usb_hid.zig b/examples/raspberrypi/rp2xxx/src/usb_hid.zig index cf12f912e..b2ed1093c 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_hid.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_hid.zig @@ -78,48 +78,46 @@ const hid_driver_options: usb.drivers.HID_Interrupt = .{ .protocol = .Boot, .itf_string = "Boot Keyboard", .poll_interval = 1, - .generic_runtime = .{ - .report_descriptor = &.{ - .{ .global_usage_page = .generic_desktop }, - .local_usage_enum(.{ .generic_desktop = .keyboard }), - .{ .main_collection = .Application }, - // Input: modifier key bitmap - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0xE0, 0xE7 }, - .count = 8, - .Child = bool, - .dir = .in, - .type = .dynamic, - } }, - // Reserved 8 bits - .{ .data_static = .{ .in, u8 } }, - // Output: indicator LEDs - .{ .data = .{ - .usage = .{ .global_page = .led }, - .usage_range = .{ 1, 5 }, - .count = 5, - .Child = bool, - .dir = .out, - .type = .dynamic, - } }, - // Padding - .{ .data_static = .{ .out, u3 } }, - // Input: up to 6 pressed key codes - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0x00, 0xff }, - .count = 6, - .Child = u8, - .dir = .in, - .type = .selector, - } }, - // End - .main_collection_end, - }, - .InReport = KeyboardInReport, - .OutReport = KeyboardOutReport, + .report_descriptor = &.{ + .{ .global_usage_page = .generic_desktop }, + .local_usage_enum(.{ .generic_desktop = .keyboard }), + .{ .main_collection = .Application }, + // Input: modifier key bitmap + .{ .data = .{ + .usage = .{ .global_page = .keyboard }, + .usage_range = .{ 0xE0, 0xE7 }, + .count = 8, + .Child = bool, + .dir = .in, + .type = .dynamic, + } }, + // Reserved 8 bits + .{ .data_static = .{ .in, u8 } }, + // Output: indicator LEDs + .{ .data = .{ + .usage = .{ .global_page = .led }, + .usage_range = .{ 1, 5 }, + .count = 5, + .Child = bool, + .dir = .out, + .type = .dynamic, + } }, + // Padding + .{ .data_static = .{ .out, u3 } }, + // Input: up to 6 pressed key codes + .{ .data = .{ + .usage = .{ .global_page = .keyboard }, + .usage_range = .{ 0x00, 0xff }, + .count = 6, + .Child = u8, + .dir = .in, + .type = .selector, + } }, + // End + .main_collection_end, }, + .InReport = KeyboardInReport, + .OutReport = KeyboardOutReport, }; var usb_device: USB_Device = undefined; diff --git a/port/nxp/mcx/build.zig.zon b/port/nxp/mcx/build.zig.zon index 0f6019884..2fb6ae318 100644 --- a/port/nxp/mcx/build.zig.zon +++ b/port/nxp/mcx/build.zig.zon @@ -4,11 +4,11 @@ .fingerprint = 0xe43e30911cb3fe37, .dependencies = .{ .@"microzig/build-internals" = .{ .path = "../../../build-internals" }, - .@"mcux-soc-svd" = .{ - .url = "https://github.com/nxp-mcuxpresso/mcux-soc-svd/archive/refs/tags/MCUX_2.16.100.tar.gz", - .hash = "N-V-__8AADdFeofKFhsuzMbDdzLAKB4-syMJsHSEOTYGFrlH", - .lazy = true, - }, + // .@"mcux-soc-svd" = .{ + // .url = "https://github.com/nxp-mcuxpresso/mcux-soc-svd/archive/refs/tags/MCUX_2.16.100.tar.gz", + // .hash = "N-V-__8AADdFeofKFhsuzMbDdzLAKB4-syMJsHSEOTYGFrlH", + // .lazy = true, + // }, }, .paths = .{ "build.zig", diff --git a/port/raspberrypi/rp2xxx/src/hal/usb.zig b/port/raspberrypi/rp2xxx/src/hal/usb.zig index 926184f31..94d3fa87d 100644 --- a/port/raspberrypi/rp2xxx/src/hal/usb.zig +++ b/port/raspberrypi/rp2xxx/src/hal/usb.zig @@ -448,39 +448,41 @@ pub fn Polled(config: Config) type { pub fn ResetDriver(bootsel_activity_led: ?u5, interface_disable_mask: u32) type { return struct { const log_drv = std.log.scoped(.pico_reset); - const Options = @This(); + + const Descriptor = extern struct { + reset_interface: usb.descriptor.Interface, + }; itf_string: []const u8 = "", - pub const Descriptor = extern struct { - reset_interface: usb.descriptor.Interface, + pub fn create_descriptor( + self: @This(), + alloc: *usb.DescriptorAllocator, + _: usb.types.PacketLength, + ) usb.DescriptorCreateResult(Descriptor) { + return .{ .descriptor = .{ .reset_interface = .{ + .interface_number = alloc.next_itf(), + .alternate_setting = 0, + .num_endpoints = 0, + .interface_triple = .from( + .VendorSpecific, + @fromBackingInt(0x00), + @fromBackingInt(0x01), + ), + .interface_s = alloc.string(self.itf_string), + } } }; + } - pub fn create( - alloc: *usb.DescriptorAllocator, - _: usb.types.PacketLength, - options: Options, - ) usb.DescriptorCreateResult(@This()) { - return .{ .descriptor = .{ .reset_interface = .{ - .interface_number = alloc.next_itf(), - .alternate_setting = 0, - .num_endpoints = 0, - .interface_triple = .from( - .VendorSpecific, - @fromBackingInt(0x00), - @fromBackingInt(0x01), - ), - .interface_s = alloc.string(options.itf_string), - } } }; - } - }; + pub fn init_runtime( + comptime _: @This(), + comptime _: Descriptor, + runtime: *Runtime, + _: *usb.DeviceInterface, + ) void { + runtime.* = .{}; + } pub const Runtime = struct { - pub fn init(self: *@This(), desc: *const Descriptor, device: *usb.DeviceInterface) void { - _ = desc; - _ = device; - self.* = .{}; - } - pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { _ = self; switch (setup.request) { From 12a25b88ffddc45be581fd427162a06e55494188 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Wed, 11 Nov 2026 13:15:04 +0100 Subject: [PATCH 14/28] Add documentation --- core/src/core/usb.zig | 4 +-- core/src/core/usb/configuration.zig | 22 -------------- core/src/core/usb/drivers/CDC.zig | 4 +-- core/src/core/usb/drivers/EchoExample.zig | 37 ++++++++++++++++++----- core/src/core/usb/drivers/HID.zig | 8 ++--- 5 files changed, 34 insertions(+), 41 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index 7b89bce02..6624de065 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -124,10 +124,10 @@ pub fn EndpointHandler(Driver: type) type { return fn (*Driver, types.Endpoint.Num) void; } -pub fn DriverHandlers(Driver: type, Runtime: type) type { +pub fn DriverHandlers(Descriptor: type, Runtime: type) type { var field_names: []const [:0]const u8 = &.{}; - const info = @typeInfo(Driver.Descriptor).@"struct"; + const info = @typeInfo(Descriptor).@"struct"; for (info.field_names, info.field_types) |field_name, field_type| switch (field_type) { descriptor.Endpoint => field_names = field_names ++ .{field_name}, else => {}, diff --git a/core/src/core/usb/configuration.zig b/core/src/core/usb/configuration.zig index fece74c3f..451809801 100644 --- a/core/src/core/usb/configuration.zig +++ b/core/src/core/usb/configuration.zig @@ -18,28 +18,6 @@ pub const Options = struct { pub fn Create( options: Options, driver_config: anytype, - // driver_args: blk: { - // const info = @typeInfo(Drivers).@"struct"; - // const count = info.field_names.len; - // var field_names: [count][:0]const u8 = undefined; - // var field_types: [count]type = undefined; - // for (info.field_names, info.field_types, 0..) |field_name, field_type, i| { - // // Collect field names - // field_names[i] = field_name; - // // Collect the type info for the Descriptor.create function parameter - // const param_types = @typeInfo(@TypeOf(field_type.Descriptor.create)).@"fn".param_types; - // // Ensure it takes 3 parameters - // assert(param_types.len == 3); - // // The first must be a DescriptorAllocator - // assert(param_types[0] == *DescriptorAllocator); - // // The second is usb.types.PacketLength - // assert(param_types[1] == types.PacketLength); - // // And save the type of the third - // assert(param_types[2] == field_type); - // field_types[i] = param_types[2].?; - // } - // break :blk @Struct(.auto, null, &field_names, &field_types, &@splat(.{})); - // }, ) type { return struct { const DriverName = []const u8; diff --git a/core/src/core/usb/drivers/CDC.zig b/core/src/core/usb/drivers/CDC.zig index a6e4d75ce..604491a9b 100644 --- a/core/src/core/usb/drivers/CDC.zig +++ b/core/src/core/usb/drivers/CDC.zig @@ -142,7 +142,7 @@ pub const Runtime = struct { // These field names are matched (at comptime) to the field names in the descriptor returned from // `create` when binding the endpoints. - pub const handlers: usb.DriverHandlers(CDC_Driver, @This()) = .{ + pub const handlers: usb.DriverHandlers(Descriptor, @This()) = .{ .ep_notifi = on_notifi_ready, .ep_out = on_rx, .ep_in = on_tx_ready, @@ -182,8 +182,6 @@ pub const Runtime = struct { } }; -const CDC_Driver = @This(); - itf_notifi_str: []const u8 = "", itf_data_str: []const u8 = "", diff --git a/core/src/core/usb/drivers/EchoExample.zig b/core/src/core/usb/drivers/EchoExample.zig index 5eafe117f..4212ec04f 100644 --- a/core/src/core/usb/drivers/EchoExample.zig +++ b/core/src/core/usb/drivers/EchoExample.zig @@ -1,27 +1,37 @@ //! This is an example driver that sends any data received on ep2 to ep1. +//! Also acts as the specification of the USB driver interface. + const std = @import("std"); const usb = @import("../../usb.zig"); const assert = std.debug.assert; const log = std.log.scoped(.usb_echo); -/// The descriptors need to have the same memory layout as the sent data. +/// Binary representation of the device descriptor as sent to the host. +/// Make sure to use `extern` layout and endian-aware field types, +/// such as `usb.types.LeInt(uXX/iXX)`. pub const Descriptor = extern struct { const desc = usb.descriptor; itf: desc.Interface, + /// Endpoint descriptor names are special. + /// Later, they are matched to endpoint handler functions ep_out: desc.Endpoint, ep_in: desc.Endpoint, }; +/// Runtime data and code associated with an instance of the driver. +/// Avoid using global variables here, so that multiple driver instances +/// can be used at the same time. pub const Runtime = struct { /// This is a mapping from endpoint descriptor field names to handler function names. - /// 'in' and 'out' are from the perspective of the host, so, usb devices send data on 'in' endpoints - /// and receive on 'out' endpoints. - pub const handlers: usb.DriverHandlers(EchoExampleDriver, @This()) = .{ + /// 'in' and 'out' are from the perspective of the host. + /// USB devices send data on 'in' endpoints and receive on 'out' endpoints. + pub const handlers: usb.DriverHandlers(Descriptor, @This()) = .{ .ep_in = on_tx_ready, .ep_out = on_rx, }; + /// Fields in this struct have no special meaning to MicroZig device: *usb.DeviceInterface, descriptor: *const Descriptor, packet_buffer: []u8, @@ -70,14 +80,25 @@ pub const Runtime = struct { } }; -pub const EchoExampleDriver = @This(); +/// `Runtime` type can be generic, in which case the driver type +/// is the only paramater passed. It may be a good idea to make this function +/// a wrapper around another, that only takes a subset of the parameters. +/// This way the generic types are much more readable in zig error output +/// and potentially less code is duplicated when using multiple driver instances +/// with different options. See HID.zig for an example. +// Each field represents a configuration option of the driver. +// The values are declared by user code and available during initialization. +// May not have any fields if the driver does not require configuration. +// Common use case for this type of configuration is for descriptor data +// that is not used by the driver at runtime, like descriptor strings. itf_string: []const u8 = "", /// This function is used during descriptor creation. Endpoint and interface numbers are -/// allocated through the `alloc` parameter. Third argument contains driver configuration. -/// If multiple instances of a driver are used, this function is called for each, -/// with different arguments. +/// allocated through the `alloc` parameter. Third argument contains the maximum supported +/// packet length, which varies by implementation. If multiple instances of a driver are used, +/// this function is called for each, with different arguments. +/// Aside from the descriptor, this function can return a type that is later used pub fn create_descriptor( self: @This(), alloc: *usb.DescriptorAllocator, diff --git a/core/src/core/usb/drivers/HID.zig b/core/src/core/usb/drivers/HID.zig index ef853ddfc..ff854c707 100644 --- a/core/src/core/usb/drivers/HID.zig +++ b/core/src/core/usb/drivers/HID.zig @@ -314,15 +314,13 @@ pub fn RuntimeGeneric(InReport: type, OutReport: type, report_descriptor: []cons _, }; - pub const Descriptor = HID_InterruptDriver.Descriptor; - - pub const handlers: usb.DriverHandlers(HID_InterruptDriver, @This()) = .{ + pub const handlers: usb.DriverHandlers(Descriptor, @This()) = .{ .ep_in = on_tx_ready, .ep_out = on_rx, }; device: *usb.DeviceInterface, - descriptor: *const @This().Descriptor, + descriptor: *const Descriptor, tx_ready: std.atomic.Value(bool), rx_ready: std.atomic.Value(bool), @@ -432,8 +430,6 @@ pub fn Runtime(self: @This()) type { const ClassCode = usb.types.ClassSubclassProtocol.ClassCode.HID; -pub const HID_InterruptDriver = @This(); - subclass: ClassCode.Subclass(), protocol: ClassCode.Protocol(), From 9523a87631ee7250d338b9327887644bf2129d9e Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Wed, 11 Nov 2026 13:59:10 +0100 Subject: [PATCH 15/28] Move runtime init back into Runtime --- core/src/core/usb.zig | 5 +- core/src/core/usb/configuration.zig | 32 +++---- core/src/core/usb/drivers/CDC.zig | 73 +++++++-------- core/src/core/usb/drivers/EchoExample.zig | 51 ++++++----- core/src/core/usb/drivers/HID.zig | 105 +++++++++++----------- port/raspberrypi/rp2xxx/src/hal/usb.zig | 99 ++++++++++---------- 6 files changed, 180 insertions(+), 185 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index 6624de065..afd2713ab 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -57,10 +57,9 @@ pub const DescriptorAllocator = struct { }; /// Wraps a Descriptor type. Returned by the `create` method of the Descriptor. -pub fn DescriptorCreateResult(Descriptor: type) type { +pub fn DriverInfo(Descriptor: type) type { return struct { - const Inner = Descriptor; - + Runtime: type, descriptor: Descriptor, /// If not null, a slice of this length will be passed /// to driver's init function. diff --git a/core/src/core/usb/configuration.zig b/core/src/core/usb/configuration.zig index 451809801..5fdbf0699 100644 --- a/core/src/core/usb/configuration.zig +++ b/core/src/core/usb/configuration.zig @@ -49,33 +49,27 @@ pub fn Create( for (driver_field_names, driver_info.field_types, 0..) |driver_field_name, DriverType, drv_id| { const drv = @field(driver_config, driver_field_name); - // Get descriptor type for the current driver - // Call the create method on the descriptor, which wraps it with the allow stuff. - const result = drv.create_descriptor(&alloc, max_psize); - const Descriptor = @TypeOf(result.descriptor); + // Get type information for the current driver + const info = drv.driver_info(&alloc, max_psize); + const Descriptor = @TypeOf(info.descriptor); + runtime_field_types[drv_id] = info.Runtime; // If the driver requests memory, then collect the names, types, and attrs - const Runtime = switch (@typeInfo(@TypeOf(DriverType.Runtime))) { - .@"fn" => drv.Runtime(), - else => DriverType.Runtime, - }; - runtime_field_types[drv_id] = Runtime; - - if (result.alloc_bytes) |len| { + if (info.alloc_bytes) |len| { driver_alloc_names = driver_alloc_names ++ &[_][:0]const u8{driver_field_name}; driver_alloc_types = driver_alloc_types ++ &[_]type{[len]u8}; - driver_alloc_attrs = driver_alloc_attrs ++ &[_]std.builtin.Type.Struct.FieldAttributes{.{ .@"align" = result.alloc_align }}; + driver_alloc_attrs = driver_alloc_attrs ++ &[_]std.builtin.Type.Struct.FieldAttributes{.{ .@"align" = info.alloc_align }}; } else { - assert(result.alloc_align == null); + assert(info.alloc_align == null); } assert(@alignOf(Descriptor) == 1); // Collect handler types, names, and drivers, to later be bound to the appropriate // endpoints - const info = @typeInfo(Descriptor).@"struct"; - for (info.field_names, info.field_types, 0..) |field_name, field_type, desc_num| { - const desc = @field(result.descriptor, field_name); + const desc_info = @typeInfo(Descriptor).@"struct"; + for (desc_info.field_names, desc_info.field_types, 0..) |field_name, field_type, desc_num| { + const desc = @field(info.descriptor, field_name); // Determine which interface numbers this driver owns. If it is an // InterfaceAssociation, then use the interface count. If it is an Interface, @@ -119,7 +113,7 @@ pub fn Create( } } desc_field_types[drv_id] = Descriptor; - field_attrs[drv_id] = .{ .default_value_ptr = &result.descriptor }; + field_attrs[drv_id] = .{ .default_value_ptr = &info.descriptor }; } // Finally, bind the handler functions based on the data collected above. @@ -217,9 +211,9 @@ pub fn Create( const runtime = &@field(driver_data, driver_field_name); // Don't pass empty slices around if (@hasField(@TypeOf(driver_alloc.*), driver_field_name)) - drv.init_runtime(cfg, runtime, device_itf, &@field(driver_alloc, driver_field_name)) + runtime.init(drv, &cfg, device_itf, &@field(driver_alloc, driver_field_name)) else - drv.init_runtime(cfg, runtime, device_itf); + runtime.init(drv, &cfg, device_itf); // Open IN endpoint last so that callbacks can happen inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { diff --git a/core/src/core/usb/drivers/CDC.zig b/core/src/core/usb/drivers/CDC.zig index 604491a9b..eccf7348e 100644 --- a/core/src/core/usb/drivers/CDC.zig +++ b/core/src/core/usb/drivers/CDC.zig @@ -5,6 +5,8 @@ const assert = microzig.assert; const usb = @import("../../usb.zig"); const log = std.log.scoped(.usb_cdc); +const Driver = @This(); + /// CDC PSTN Subclass Management Element Requests pub const ManagementRequestType = enum(u8) { SetCommFeature = 0x02, @@ -140,6 +142,36 @@ pub const Runtime = struct { // *** USB driver interface below *** + // Called when the host selects a configuration. + pub fn init( + self: *Runtime, + _: Driver, + descriptor: *const Descriptor, + device: *usb.DeviceInterface, + data: []u8, + ) void { + const len_half = @divExact(data.len, 2); + assert(len_half == descriptor.ep_in.max_packet_size.native(), .{}); + assert(len_half == descriptor.ep_out.max_packet_size.native(), .{}); + self.* = .{ + .device = device, + .descriptor = descriptor, + .line_coding = .init, + .notifi_ready = .init(true), + + // `init` provides a data buffer, which we split in half for rx and tx data. + .rx_data = data[0..len_half], + .rx_seek = 0, + .rx_end = 0, + .rx_ready = .init(false), + + .tx_data = data[len_half..], + .tx_end = 0, + .tx_ready = .init(true), + }; + device.ep_listen(descriptor.ep_out.endpoint.num, @intCast(self.rx_data.len)); + } + // These field names are matched (at comptime) to the field names in the descriptor returned from // `create` when binding the endpoints. pub const handlers: usb.DriverHandlers(Descriptor, @This()) = .{ @@ -190,16 +222,18 @@ itf_data_str: []const u8 = "", /// by the user when creating the device controller type. If multiple instances of a driver /// are used, this function is called for each, with different arguments. Passing arguments /// through this function is preferred to making the whole driver generic. -pub fn create_descriptor( - comptime self: @This(), +pub fn driver_info( + self: @This(), alloc: *usb.DescriptorAllocator, - max_supported_packet_size: usb.types.PacketLength, -) usb.DescriptorCreateResult(Descriptor) { + comptime max_supported_packet_size: usb.types.PacketLength, +) usb.DriverInfo(Descriptor) { // Endpoint and interface numbers are allocated through the `alloc` parameter, // so that multiple instances of this driver can coexist. const itf_notifi = alloc.next_itf(); const itf_data = alloc.next_itf(); return .{ + .Runtime = Runtime, + .alloc_bytes = 2 * max_supported_packet_size, .descriptor = .{ .itf_assoc = .{ .first_interface = itf_notifi, @@ -253,36 +287,5 @@ pub fn create_descriptor( .ep_out = .bulk(alloc.next_ep(.out), max_supported_packet_size), .ep_in = .bulk(alloc.next_ep(.in), max_supported_packet_size), }, - .alloc_bytes = 2 * max_supported_packet_size, - }; -} - -// Called when the host selects a configuration. -pub fn init_runtime( - comptime _: @This(), - comptime descriptor: Descriptor, - runtime: *Runtime, - device: *usb.DeviceInterface, - data: []u8, -) void { - const len_half = @divExact(data.len, 2); - assert(len_half == descriptor.ep_in.max_packet_size.native(), .{}); - assert(len_half == descriptor.ep_out.max_packet_size.native(), .{}); - runtime.* = .{ - .device = device, - .descriptor = &descriptor, - .line_coding = .init, - .notifi_ready = .init(true), - - // `init` provides a data buffer, which we split in half for rx and tx data. - .rx_data = data[0..len_half], - .rx_seek = 0, - .rx_end = 0, - .rx_ready = .init(false), - - .tx_data = data[len_half..], - .tx_end = 0, - .tx_ready = .init(true), }; - device.ep_listen(descriptor.ep_out.endpoint.num, @intCast(runtime.rx_data.len)); } diff --git a/core/src/core/usb/drivers/EchoExample.zig b/core/src/core/usb/drivers/EchoExample.zig index 4212ec04f..1111a6792 100644 --- a/core/src/core/usb/drivers/EchoExample.zig +++ b/core/src/core/usb/drivers/EchoExample.zig @@ -6,6 +6,8 @@ const usb = @import("../../usb.zig"); const assert = std.debug.assert; const log = std.log.scoped(.usb_echo); +const Driver = @This(); + /// Binary representation of the device descriptor as sent to the host. /// Make sure to use `extern` layout and endian-aware field types, /// such as `usb.types.LeInt(uXX/iXX)`. @@ -37,6 +39,28 @@ pub const Runtime = struct { packet_buffer: []u8, tx_ready: std.atomic.Value(bool), + /// This function is called when the host chooses a configuration that contains this driver. `self` + /// points to undefined memory. `data` is of the length specified in `Descriptor.create()`. + pub fn init( + self: *@This(), + _: Driver, + descriptor: *const Descriptor, + device: *usb.DeviceInterface, + data: []u8, + ) void { + assert(data.len == descriptor.ep_in.max_packet_size.native()); + self.* = .{ + .device = device, + .descriptor = descriptor, + .packet_buffer = data, + .tx_ready = .init(false), + }; + device.ep_listen( + descriptor.ep_out.endpoint.num, + @intCast(descriptor.ep_out.max_packet_size.native()), + ); + } + /// Used for interface configuration through endpoint 0. /// Data returned by this function is sent on endpoint 0. pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { @@ -99,12 +123,13 @@ itf_string: []const u8 = "", /// packet length, which varies by implementation. If multiple instances of a driver are used, /// this function is called for each, with different arguments. /// Aside from the descriptor, this function can return a type that is later used -pub fn create_descriptor( +pub fn driver_info( self: @This(), alloc: *usb.DescriptorAllocator, max_supported_packet_size: usb.types.PacketLength, -) usb.DescriptorCreateResult(Descriptor) { +) usb.DriverInfo(Descriptor) { return .{ + .Runtime = Runtime, .descriptor = .{ .itf = .{ .interface_number = alloc.next_itf(), @@ -121,25 +146,3 @@ pub fn create_descriptor( .alloc_bytes = max_supported_packet_size, }; } - -/// This function is called when the host chooses a configuration that contains this driver. `self` -/// points to undefined memory. `data` is of the length specified in `Descriptor.create()`. -pub fn init_runtime( - comptime _: @This(), - comptime desc: Descriptor, - runtime: *Runtime, - device: *usb.DeviceInterface, - data: []u8, -) void { - assert(data.len == desc.ep_in.max_packet_size.native()); - runtime.* = .{ - .device = device, - .descriptor = &desc, - .packet_buffer = data, - .tx_ready = .init(false), - }; - device.ep_listen( - desc.ep_out.endpoint.num, - @intCast(desc.ep_out.max_packet_size.native()), - ); -} diff --git a/core/src/core/usb/drivers/HID.zig b/core/src/core/usb/drivers/HID.zig index ff854c707..555a8637d 100644 --- a/core/src/core/usb/drivers/HID.zig +++ b/core/src/core/usb/drivers/HID.zig @@ -3,6 +3,8 @@ const usb = @import("../../usb.zig"); const assert = std.debug.assert; const log = std.log.scoped(.usb_hid_int_driver); +const Driver = @This(); + /// Reports are a list of tagged ?i32 values. Encoding is variable-length. pub const ReportItem = union(enum) { pub const Header = packed struct(u8) { @@ -302,7 +304,7 @@ pub const Descriptor = extern struct { }; /// HID Driver with an IN and OUT endpoint -pub fn RuntimeGeneric(InReport: type, OutReport: type, report_descriptor: []const u8) type { +pub fn Runtime(InReport: type, OutReport: type, report_descriptor: []const u8) type { return struct { pub const RequestType = enum(u8) { GetReport = 0x01, @@ -324,6 +326,25 @@ pub fn RuntimeGeneric(InReport: type, OutReport: type, report_descriptor: []cons tx_ready: std.atomic.Value(bool), rx_ready: std.atomic.Value(bool), + pub fn init( + self: *@This(), + _: Driver, + descriptor: *const Descriptor, + device: *usb.DeviceInterface, + ) void { + log.debug("init", .{}); + self.* = .{ + .device = device, + .descriptor = descriptor, + .tx_ready = .init(true), + .rx_ready = .init(false), + }; + device.ep_listen( + descriptor.ep_out.endpoint.num, + @intCast(descriptor.ep_out.max_packet_size.native()), + ); + } + pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { log.debug("class_request {any}", .{setup}); switch (setup.request_type.type) { @@ -420,14 +441,6 @@ pub fn RuntimeGeneric(InReport: type, OutReport: type, report_descriptor: []cons }; } -pub fn Runtime(self: @This()) type { - return RuntimeGeneric( - self.InReport, - self.OutReport, - ReportItem.create_report(self.report_descriptor), - ); -} - const ClassCode = usb.types.ClassSubclassProtocol.ClassCode.HID; subclass: ClassCode.Subclass(), @@ -440,54 +453,42 @@ report_descriptor: []const ?ReportItem, InReport: type, OutReport: type, -pub fn create_descriptor( +pub fn driver_info( comptime self: @This(), alloc: *usb.DescriptorAllocator, max_supported_packet_size: usb.types.PacketLength, -) usb.DescriptorCreateResult(Descriptor) { +) usb.DriverInfo(Descriptor) { assert(@sizeOf(self.InReport) <= max_supported_packet_size); assert(@sizeOf(self.OutReport) <= max_supported_packet_size); - return .{ .descriptor = .{ - .interface = .{ - .interface_number = alloc.next_itf(), - .alternate_setting = 0, - .num_endpoints = 2, - .interface_triple = .from(.HID, self.subclass, self.protocol), - .interface_s = alloc.string(self.itf_string), - }, - .hid = .{ - .country_code = self.country_code, - .num_descriptors = 1, - .report_length = .from(self.report_descriptor.len), - }, - .ep_out = .interrupt( - alloc.next_ep(.out), - @sizeOf(self.OutReport), - self.poll_interval, + return .{ + .Runtime = Runtime( + self.InReport, + self.OutReport, + ReportItem.create_report(self.report_descriptor), ), - .ep_in = .interrupt( - alloc.next_ep(.in), - @sizeOf(self.InReport), - self.poll_interval, - ), - } }; -} - -pub fn init_runtime( - comptime self: @This(), - comptime descriptor: Descriptor, - runtime: *self.Runtime(), - device: *usb.DeviceInterface, -) void { - log.debug("init", .{}); - runtime.* = .{ - .device = device, - .descriptor = &descriptor, - .tx_ready = .init(true), - .rx_ready = .init(false), + .descriptor = .{ + .interface = .{ + .interface_number = alloc.next_itf(), + .alternate_setting = 0, + .num_endpoints = 2, + .interface_triple = .from(.HID, self.subclass, self.protocol), + .interface_s = alloc.string(self.itf_string), + }, + .hid = .{ + .country_code = self.country_code, + .num_descriptors = 1, + .report_length = .from(self.report_descriptor.len), + }, + .ep_out = .interrupt( + alloc.next_ep(.out), + @sizeOf(self.OutReport), + self.poll_interval, + ), + .ep_in = .interrupt( + alloc.next_ep(.in), + @sizeOf(self.InReport), + self.poll_interval, + ), + }, }; - device.ep_listen( - descriptor.ep_out.endpoint.num, - @intCast(descriptor.ep_out.max_packet_size.native()), - ); } diff --git a/port/raspberrypi/rp2xxx/src/hal/usb.zig b/port/raspberrypi/rp2xxx/src/hal/usb.zig index 94d3fa87d..ab3f98d33 100644 --- a/port/raspberrypi/rp2xxx/src/hal/usb.zig +++ b/port/raspberrypi/rp2xxx/src/hal/usb.zig @@ -446,65 +446,60 @@ pub fn Polled(config: Config) type { } pub fn ResetDriver(bootsel_activity_led: ?u5, interface_disable_mask: u32) type { - return struct { - const log_drv = std.log.scoped(.pico_reset); + const log_drv = std.log.scoped(.pico_reset); - const Descriptor = extern struct { - reset_interface: usb.descriptor.Interface, - }; + const Descriptor = extern struct { + reset_interface: usb.descriptor.Interface, + }; + + const Runtime = struct { + pub fn init(_: *@This(), _: anytype, _: *const Descriptor, _: *usb.DeviceInterface) void {} + + pub fn class_request(_: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { + switch (setup.request) { + 0x01 => { + const value = setup.value.native(); + const mask = @as(u32, 1) << if (value & 0x100 != 0) + @intCast(value >> 9) + else + bootsel_activity_led orelse 0; + const itf_disable = (value & 0x7F) | interface_disable_mask; + log_drv.debug("Resetting to bootsel. Mask: {} Itf disable: {}", .{ mask, itf_disable }); + microzig.hal.rom.reset_to_usb_boot(); + }, + 0x02 => { + log_drv.debug("Resetting to flash", .{}); + // Not implemented yet + microzig.hal.rom.reset_to_usb_boot(); + }, + else => return usb.nak, + } + return usb.ack; + } + }; + return struct { itf_string: []const u8 = "", - pub fn create_descriptor( + pub fn driver_info( self: @This(), alloc: *usb.DescriptorAllocator, _: usb.types.PacketLength, - ) usb.DescriptorCreateResult(Descriptor) { - return .{ .descriptor = .{ .reset_interface = .{ - .interface_number = alloc.next_itf(), - .alternate_setting = 0, - .num_endpoints = 0, - .interface_triple = .from( - .VendorSpecific, - @fromBackingInt(0x00), - @fromBackingInt(0x01), - ), - .interface_s = alloc.string(self.itf_string), - } } }; - } - - pub fn init_runtime( - comptime _: @This(), - comptime _: Descriptor, - runtime: *Runtime, - _: *usb.DeviceInterface, - ) void { - runtime.* = .{}; + ) usb.DriverInfo(Descriptor) { + return .{ + .Runtime = Runtime, + .descriptor = .{ .reset_interface = .{ + .interface_number = alloc.next_itf(), + .alternate_setting = 0, + .num_endpoints = 0, + .interface_triple = .from( + .VendorSpecific, + @fromBackingInt(0x00), + @fromBackingInt(0x01), + ), + .interface_s = alloc.string(self.itf_string), + } }, + }; } - - pub const Runtime = struct { - pub fn class_request(self: *@This(), setup: *const usb.types.SetupPacket) ?[]const u8 { - _ = self; - switch (setup.request) { - 0x01 => { - const value = setup.value.native(); - const mask = @as(u32, 1) << if (value & 0x100 != 0) - @intCast(value >> 9) - else - bootsel_activity_led orelse 0; - const itf_disable = (value & 0x7F) | interface_disable_mask; - log_drv.debug("Resetting to bootsel. Mask: {} Itf disable: {}", .{ mask, itf_disable }); - microzig.hal.rom.reset_to_usb_boot(); - }, - 0x02 => { - log_drv.debug("Resetting to flash", .{}); - // Not implemented yet - microzig.hal.rom.reset_to_usb_boot(); - }, - else => return usb.nak, - } - return usb.ack; - } - }; }; } From bbadbaa3578890c55858c9f9d1718d28e67057fa Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Wed, 11 Nov 2026 14:50:44 +0100 Subject: [PATCH 16/28] Introduce DeviceCapabilities struct --- core/src/core/usb.zig | 62 ++++++++++++++----- core/src/core/usb/configuration.zig | 4 +- core/src/core/usb/drivers/CDC.zig | 10 +-- core/src/core/usb/drivers/EchoExample.zig | 8 +-- core/src/core/usb/drivers/HID.zig | 6 +- examples/nordic/nrf5x/src/usb_cdc.zig | 5 +- examples/nordic/nrf5x/src/usb_hid.zig | 5 +- examples/raspberrypi/rp2xxx/src/usb_cdc.zig | 5 +- examples/raspberrypi/rp2xxx/src/usb_hid.zig | 5 +- .../raspberrypi/rp2xxx/src/usb_raw_echo.zig | 5 +- examples/wch/ch32v/src/usb_cdc.zig | 6 +- port/nordic/nrf5x/src/hal/usbd.zig | 15 +++-- port/raspberrypi/rp2xxx/src/hal/usb.zig | 29 +++++---- port/wch/ch32v/src/hals/usbd.zig | 10 +++ port/wch/ch32v/src/hals/usbfs.zig | 17 +++-- port/wch/ch32v/src/hals/usbhs.zig | 16 +++-- 16 files changed, 131 insertions(+), 77 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index afd2713ab..5de875552 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -56,6 +56,17 @@ pub const DescriptorAllocator = struct { } }; +/// Device-specific information +pub const DeviceCapabilities = struct { + max_supported_bcd_usb: types.Version = .v1_00, + /// Maximimum packet size on ep0 + max_packet_size0: types.PacketLength, + /// Maximimum packet size on other endpoints + max_packet_size: types.PacketLength, + default_vendor: ?Options.IdStringPair = null, + default_product: ?Options.IdStringPair = null, +}; + /// Wraps a Descriptor type. Returned by the `create` method of the Descriptor. pub fn DriverInfo(Descriptor: type) type { return struct { @@ -141,14 +152,14 @@ pub const Options = struct { str: []const u8, }; - /// Usb specification version. - bcd_usb: types.Version, + /// Usb specification version. `null` means highest supported by device. + bcd_usb: ?types.Version = null, /// Class, subclass and protocol of this device. device_triple: types.ClassSubclassProtocol, - /// Vendor id and string - vendor: IdStringPair, - /// Product id and string. - product: IdStringPair, + /// Vendor id and string. `null` means default provided by device + vendor: ?IdStringPair = null, + /// Product id and string. `null` means default provided by device + product: ?IdStringPair = null, /// Device version. bcd_device: types.Version, /// String descriptor 0. @@ -156,7 +167,7 @@ pub const Options = struct { /// Serial number string. serial: []const u8, /// Largest packet length the hardware supports. Must be a power of 2 and at least 8. - max_supported_packet_size: types.PacketLength, + device_capabilities: DeviceCapabilities, }; pub fn validate_controller(T: type) void { @@ -170,6 +181,14 @@ pub fn validate_controller(T: type) void { } } +pub fn validate_device(Device: type) void { + if (!@hasDecl(Device, "device_capabilities")) + @compileError("USB device " ++ @typeName(Device) ++ " is missing a device_capabilities declaration."); + if (@TypeOf(Device.device_capabilities) != DeviceCapabilities) + @compileError("USB device " ++ @typeName(Device) ++ ".device_capabilities has incorrect type.\n" ++ + "Got: " ++ @typeName(@TypeOf(DeviceCapabilities)) ++ ", expected usb.DeviceCapabilities"); +} + /// USB device controller /// /// Responds to host requests and dispatches to the appropriate drivers. @@ -185,21 +204,30 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { /// * table of handlers for endpoints /// * table of handlers for interfaces const descriptor_parse_result = blk: { - const max_psize = options.max_supported_packet_size; - assert(max_psize >= 8); - assert(std.math.isPowerOfTwo(max_psize)); + const max_psize0 = options.device_capabilities.max_packet_size0; + const max_psize = options.device_capabilities.max_packet_size; + if (max_psize0 < 8 or !std.math.isPowerOfTwo(max_psize0) or max_psize < 8 or !std.math.isPowerOfTwo(max_psize)) + @compileError("Maximum packet size must be a power of two and at least 8"); + + const vendor = options.vendor orelse + (options.device_capabilities.default_vendor orelse + @compileError("Vendor ID not provided and device does not specify a default.")); + + const product = options.product orelse + (options.device_capabilities.default_product orelse + @compileError("Product ID not provided and device does not specify a default.")); var strings: []const []const u8 = &.{}; - strings, const manufacturer_s = dedup_string(strings, options.vendor.str); - strings, const product_s = dedup_string(strings, options.product.str); + strings, const manufacturer_s = dedup_string(strings, vendor.str); + strings, const product_s = dedup_string(strings, product.str); strings, const serial_s = dedup_string(strings, options.serial); const desc_device: descriptor.Device = .{ - .bcd_usb = options.bcd_usb, + .bcd_usb = options.bcd_usb orelse options.device_capabilities.max_supported_bcd_usb, .device_triple = options.device_triple, - .max_packet_size0 = @min(options.max_supported_packet_size, 64), - .vendor = .from(options.vendor.id), - .product = .from(options.product.id), + .max_packet_size0 = max_psize0, + .vendor = .from(vendor.id), + .product = .from(product.id), .bcd_device = options.bcd_device, .manufacturer_s = manufacturer_s, .product_s = product_s, @@ -209,7 +237,7 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { var configs: @Tuple(Configurations) = undefined; for (0..Configurations.len) |i| - configs[i], strings = Configurations[i].create(max_psize, strings); + configs[i], strings = Configurations[i].create(options.device_capabilities, strings); var desc_string: []const descriptor.String = &.{.from_lang(options.language)}; for (strings) |s| diff --git a/core/src/core/usb/configuration.zig b/core/src/core/usb/configuration.zig index 5fdbf0699..78dbe2f21 100644 --- a/core/src/core/usb/configuration.zig +++ b/core/src/core/usb/configuration.zig @@ -29,7 +29,7 @@ pub fn Create( handlers_itf: []const DriverName, RuntimeData: type, - pub fn create(max_psize: types.PacketLength, strings: []const []const u8) struct { @This(), []const []const u8 } { + pub fn create(device_capabilities: usb.DeviceCapabilities, strings: []const []const u8) struct { @This(), []const []const u8 } { var alloc = usb.DescriptorAllocator.init(options.unique_endpoints, strings); const configuration_s = alloc.string(options.name); const driver_info = @typeInfo(@TypeOf(driver_config)).@"struct"; @@ -50,7 +50,7 @@ pub fn Create( const drv = @field(driver_config, driver_field_name); // Get type information for the current driver - const info = drv.driver_info(&alloc, max_psize); + const info = drv.driver_info(device_capabilities, &alloc); const Descriptor = @TypeOf(info.descriptor); runtime_field_types[drv_id] = info.Runtime; diff --git a/core/src/core/usb/drivers/CDC.zig b/core/src/core/usb/drivers/CDC.zig index eccf7348e..b60de5bed 100644 --- a/core/src/core/usb/drivers/CDC.zig +++ b/core/src/core/usb/drivers/CDC.zig @@ -224,8 +224,8 @@ itf_data_str: []const u8 = "", /// through this function is preferred to making the whole driver generic. pub fn driver_info( self: @This(), + comptime device_capabilities: usb.DeviceCapabilities, alloc: *usb.DescriptorAllocator, - comptime max_supported_packet_size: usb.types.PacketLength, ) usb.DriverInfo(Descriptor) { // Endpoint and interface numbers are allocated through the `alloc` parameter, // so that multiple instances of this driver can coexist. @@ -233,7 +233,7 @@ pub fn driver_info( const itf_data = alloc.next_itf(); return .{ .Runtime = Runtime, - .alloc_bytes = 2 * max_supported_packet_size, + .alloc_bytes = 2 * device_capabilities.max_packet_size, .descriptor = .{ .itf_assoc = .{ .first_interface = itf_notifi, @@ -275,7 +275,7 @@ pub fn driver_info( .ep_notifi = .interrupt( alloc.next_ep(.in), 8, - if (max_supported_packet_size > 64) 8 else 16, + if (device_capabilities.max_packet_size > 64) 8 else 16, ), .itf_data = .{ .interface_number = itf_data, @@ -284,8 +284,8 @@ pub fn driver_info( .interface_triple = .from(.CDC_Data, .Unused, .NoneRequired), .interface_s = alloc.string(self.itf_data_str), }, - .ep_out = .bulk(alloc.next_ep(.out), max_supported_packet_size), - .ep_in = .bulk(alloc.next_ep(.in), max_supported_packet_size), + .ep_out = .bulk(alloc.next_ep(.out), device_capabilities.max_packet_size), + .ep_in = .bulk(alloc.next_ep(.in), device_capabilities.max_packet_size), }, }; } diff --git a/core/src/core/usb/drivers/EchoExample.zig b/core/src/core/usb/drivers/EchoExample.zig index 1111a6792..eb8e242b4 100644 --- a/core/src/core/usb/drivers/EchoExample.zig +++ b/core/src/core/usb/drivers/EchoExample.zig @@ -125,8 +125,8 @@ itf_string: []const u8 = "", /// Aside from the descriptor, this function can return a type that is later used pub fn driver_info( self: @This(), + comptime device_capabilities: usb.DeviceCapabilities, alloc: *usb.DescriptorAllocator, - max_supported_packet_size: usb.types.PacketLength, ) usb.DriverInfo(Descriptor) { return .{ .Runtime = Runtime, @@ -138,11 +138,11 @@ pub fn driver_info( .interface_triple = .vendor_specific, .interface_s = alloc.string(self.itf_string), }, - .ep_out = .bulk(alloc.next_ep(.out), max_supported_packet_size), - .ep_in = .bulk(alloc.next_ep(.in), max_supported_packet_size), + .ep_out = .bulk(alloc.next_ep(.out), device_capabilities.max_packet_size), + .ep_in = .bulk(alloc.next_ep(.in), device_capabilities.max_packet_size), }, // Buffers whose length is only known after creating the // descriptor can be allocated at this stage. - .alloc_bytes = max_supported_packet_size, + .alloc_bytes = device_capabilities.max_packet_size, }; } diff --git a/core/src/core/usb/drivers/HID.zig b/core/src/core/usb/drivers/HID.zig index 555a8637d..6d1395f1d 100644 --- a/core/src/core/usb/drivers/HID.zig +++ b/core/src/core/usb/drivers/HID.zig @@ -455,11 +455,11 @@ OutReport: type, pub fn driver_info( comptime self: @This(), + comptime device_capabilities: usb.DeviceCapabilities, alloc: *usb.DescriptorAllocator, - max_supported_packet_size: usb.types.PacketLength, ) usb.DriverInfo(Descriptor) { - assert(@sizeOf(self.InReport) <= max_supported_packet_size); - assert(@sizeOf(self.OutReport) <= max_supported_packet_size); + assert(@sizeOf(self.InReport) <= device_capabilities.max_packet_size); + assert(@sizeOf(self.OutReport) <= device_capabilities.max_packet_size); return .{ .Runtime = Runtime( self.InReport, diff --git a/examples/nordic/nrf5x/src/usb_cdc.zig b/examples/nordic/nrf5x/src/usb_cdc.zig index 0f23be203..9e417e28e 100644 --- a/examples/nordic/nrf5x/src/usb_cdc.zig +++ b/examples/nordic/nrf5x/src/usb_cdc.zig @@ -31,13 +31,10 @@ var usb_device: USBD = undefined; // Generate a device controller with descriptor and handlers setup for CDC (usb.drivers.CDC) var usb_controller: usb.DeviceController(.{ - .bcd_usb = USBD.max_supported_bcd_usb, .device_triple = .unspecified, - .vendor = USBD.default_vendor_id, - .product = USBD.default_product_id, .bcd_device = .v1_00, .serial = "someserial", - .max_supported_packet_size = USBD.max_supported_packet_size, + .device_capabilities = USBD.device_capabilities, }, &.{usb.configuration.Create( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ .serial = usb.drivers.CDC{ .itf_notifi_str = "Board CDC", .itf_data_str = "Board CDC Data" } }, diff --git a/examples/nordic/nrf5x/src/usb_hid.zig b/examples/nordic/nrf5x/src/usb_hid.zig index a4aadbb6c..c59f094fb 100644 --- a/examples/nordic/nrf5x/src/usb_hid.zig +++ b/examples/nordic/nrf5x/src/usb_hid.zig @@ -130,13 +130,10 @@ const hid_driver_options: usb.drivers.HID_Interrupt = .{ var usb_device: USBD = undefined; var usb_controller: usb.DeviceController(.{ - .bcd_usb = USBD.max_supported_bcd_usb, .device_triple = .unspecified, - .vendor = USBD.default_vendor_id, - .product = USBD.default_product_id, .bcd_device = .v1_00, .serial = "someserial", - .max_supported_packet_size = USBD.max_supported_packet_size, + .device_capabilities = USBD.device_capabilities, }, &.{usb.configuration.Create( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ .keyboard = hid_driver_options }, diff --git a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig index c9d354861..e340675a4 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig @@ -14,13 +14,10 @@ var usb_device: USB_Device = undefined; // Generate a device controller with descriptor and handlers setup for CDC (usb.drivers.CDC) and // picotool-controlled reset (ResetDriver). var usb_controller: usb.DeviceController(.{ - .bcd_usb = USB_Device.max_supported_bcd_usb, .device_triple = .unspecified, - .vendor = USB_Device.default_vendor_id, - .product = USB_Device.default_product_id, .bcd_device = .v1_00, .serial = "someserial", - .max_supported_packet_size = USB_Device.max_supported_packet_size, + .device_capabilities = USB_Device.device_capabilities, }, &.{usb.configuration.Create( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ diff --git a/examples/raspberrypi/rp2xxx/src/usb_hid.zig b/examples/raspberrypi/rp2xxx/src/usb_hid.zig index b2ed1093c..111699520 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_hid.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_hid.zig @@ -123,13 +123,10 @@ const hid_driver_options: usb.drivers.HID_Interrupt = .{ var usb_device: USB_Device = undefined; var usb_controller: usb.DeviceController(.{ - .bcd_usb = USB_Device.max_supported_bcd_usb, .device_triple = .unspecified, - .vendor = USB_Device.default_vendor_id, - .product = USB_Device.default_product_id, .bcd_device = .v1_00, .serial = "someserial", - .max_supported_packet_size = USB_Device.max_supported_packet_size, + .device_capabilities = USB_Device.device_capabilities, }, &.{usb.configuration.Create( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ diff --git a/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig b/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig index 3d70250b7..ae59afd41 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig @@ -13,13 +13,10 @@ var usb_device: USB_Device = undefined; // Generate a device controller with descriptor and handlers setup for CDC (USB_Serial) and // picotool-controlled reset (ResetDriver). var usb_controller: usb.DeviceController(.{ - .bcd_usb = USB_Device.max_supported_bcd_usb, .device_triple = .unspecified, - .vendor = USB_Device.default_vendor_id, - .product = USB_Device.default_product_id, .bcd_device = .v1_00, .serial = "someserial", - .max_supported_packet_size = USB_Device.max_supported_packet_size, + .device_capabilities = USB_Device.device_capabilities, }, &.{usb.configuration.Create( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ diff --git a/examples/wch/ch32v/src/usb_cdc.zig b/examples/wch/ch32v/src/usb_cdc.zig index 4feb73a27..047e7c8bc 100644 --- a/examples/wch/ch32v/src/usb_cdc.zig +++ b/examples/wch/ch32v/src/usb_cdc.zig @@ -23,6 +23,8 @@ comptime { _ = microzig.export_startup(); } +const USB_Device = hal.usb.Polled(board.usb_setup, .{}); + const USB_Controller = usb.DeviceController(.{ .bcd_usb = .v2_00, .device_triple = .unspecified, @@ -30,13 +32,13 @@ const USB_Controller = usb.DeviceController(.{ .product = .{ .id = 0x0001, .str = board.product_string }, .bcd_device = .v1_00, .serial = "someserial", - .max_supported_packet_size = hal.usb.max_packet_size, + .device_capabilities = USB_Device.device_capabilities, }, &.{usb.configuration.Create( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ .serial = usb.drivers.CDC{ .itf_notifi_str = "Board CDC", .itf_data_str = "Board CDC Data" } }, )}); -pub var usb_dev: hal.usb.Polled(board.usb_setup, .{}) = undefined; +pub var usb_dev: USB_Device = undefined; var usb_controller: USB_Controller = .init; diff --git a/port/nordic/nrf5x/src/hal/usbd.zig b/port/nordic/nrf5x/src/hal/usbd.zig index 670b333a2..322ba829e 100644 --- a/port/nordic/nrf5x/src/hal/usbd.zig +++ b/port/nordic/nrf5x/src/hal/usbd.zig @@ -50,10 +50,17 @@ pub const USBD = struct { interface: usb.DeviceInterface, - pub const max_supported_packet_size = MAX_PACKET_SIZE; - pub const max_supported_bcd_usb: usb.types.Version = .v1_10; - pub const default_vendor_id: usb.Options.IdStringPair = .{ .id = 0x1209, .str = "pid.codes" }; - pub const default_product_id: usb.Options.IdStringPair = .{ .id = 0x0001, .str = "nRF5x test device" }; + pub const device_capabilities: usb.DeviceCapabilities = .{ + .max_supported_bcd_usb = .v1_10, + .max_packet_size0 = MAX_PACKET_SIZE, + .max_packet_size = MAX_PACKET_SIZE, + .default_vendor = .{ .id = 0x1209, .str = "pid.codes" }, + .default_product = .{ .id = 0x0001, .str = "nRF5x test device" }, + }; + + comptime { + usb.validate_device(@This()); + } const vtable: usb.DeviceInterface.VTable = .{ .ep_writev = ep_writev, diff --git a/port/raspberrypi/rp2xxx/src/hal/usb.zig b/port/raspberrypi/rp2xxx/src/hal/usb.zig index ab3f98d33..ddfb8acdc 100644 --- a/port/raspberrypi/rp2xxx/src/hal/usb.zig +++ b/port/raspberrypi/rp2xxx/src/hal/usb.zig @@ -84,14 +84,21 @@ pub fn Polled(config: Config) type { } return struct { - pub const max_supported_packet_size = 64; - pub const max_supported_bcd_usb: usb.types.Version = .v1_10; - pub const default_vendor_id: usb.Options.IdStringPair = .{ .id = 0x2E8A, .str = "Raspberry Pi" }; - pub const default_product_id: usb.Options.IdStringPair = switch (chip) { - .RP2040 => .{ .id = 0x000A, .str = "Pico test device" }, - .RP2350 => .{ .id = 0x000F, .str = "Pico 2 test device" }, + pub const device_capabilities: usb.DeviceCapabilities = .{ + .max_supported_bcd_usb = .v1_10, + .max_packet_size0 = 64, + .max_packet_size = 64, + .default_vendor = .{ .id = 0x2E8A, .str = "Raspberry Pi" }, + .default_product = switch (chip) { + .RP2040 => .{ .id = 0x000A, .str = "Pico test device" }, + .RP2350 => .{ .id = 0x000F, .str = "Pico 2 test device" }, + }, }; + comptime { + usb.validate_device(@This()); + } + const vtable: usb.DeviceInterface.VTable = .{ .ep_writev = ep_writev, .ep_readv = ep_readv, @@ -246,15 +253,15 @@ pub fn Polled(config: Config) type { @memset(std.mem.asBytes(&self.endpoints), 0); // Set up endpoints. - self.interface.ep_open(&.control(.in(.ep0), max_supported_packet_size)); - self.interface.ep_open(&.control(.out(.ep0), max_supported_packet_size)); + self.interface.ep_open(&.control(.in(.ep0), device_capabilities.max_packet_size)); + self.interface.ep_open(&.control(.out(.ep0), device_capabilities.max_packet_size)); // Present full-speed device by enabling pullup on DP. This is the point // where the host will notice our presence. peripherals.USB.SIE_CTRL.modify(.{ .PULLUP_EN = 1 }); // Listen for ACKs - self.interface.ep_listen(.ep0, max_supported_packet_size); + self.interface.ep_listen(.ep0, device_capabilities.max_packet_size); return self; } @@ -411,7 +418,7 @@ pub fn Polled(config: Config) type { const ep_hard = self.hardware_endpoint_get_by_address(ep); - assert(desc.max_packet_size.native() <= max_supported_packet_size); + assert(desc.max_packet_size.native() <= device_capabilities.max_packet_size); buffer_control[@backingInt(ep.num)].get(ep.dir).modify(.{ .PID_0 = 1 }); @@ -483,8 +490,8 @@ pub fn ResetDriver(bootsel_activity_led: ?u5, interface_disable_mask: u32) type pub fn driver_info( self: @This(), + comptime _: usb.DeviceCapabilities, alloc: *usb.DescriptorAllocator, - _: usb.types.PacketLength, ) usb.DriverInfo(Descriptor) { return .{ .Runtime = Runtime, diff --git a/port/wch/ch32v/src/hals/usbd.zig b/port/wch/ch32v/src/hals/usbd.zig index 149c00450..b708f9167 100644 --- a/port/wch/ch32v/src/hals/usbd.zig +++ b/port/wch/ch32v/src/hals/usbd.zig @@ -327,6 +327,16 @@ pub fn Polled(comptime setup: Setup, comptime cfg: Config) type { return struct { const Self = @This(); + pub const device_capabilities: usb.DeviceCapabilities = .{ + .max_supported_bcd_usb = .v2_00, // Is this correct? + .max_packet_size0 = 64, + .max_packet_size = 64, + }; + + comptime { + usb.validate_device(@This()); + } + const vtable: usb.DeviceInterface.VTable = .{ .ep_writev = ep_writev, .ep_readv = ep_readv, diff --git a/port/wch/ch32v/src/hals/usbfs.zig b/port/wch/ch32v/src/hals/usbfs.zig index f45596d3e..bcdbde8f7 100644 --- a/port/wch/ch32v/src/hals/usbfs.zig +++ b/port/wch/ch32v/src/hals/usbfs.zig @@ -10,9 +10,6 @@ const peripherals = microzig.chip.peripherals; const usb = microzig.core.usb; const types = usb.types; const descriptor = usb.descriptor; - -pub const max_packet_size: u11 = 64; - pub const USB_MAX_ENDPOINTS_COUNT = 8; const max_buffer_pool_size = USB_MAX_ENDPOINTS_COUNT * 2 * 64 + 64; @@ -156,6 +153,16 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { return struct { const Self = @This(); + pub const device_capabilities: usb.DeviceCapabilities = .{ + .max_supported_bcd_usb = .v2_00, // Is this correct? + .max_packet_size0 = 64, + .max_packet_size = 64, + }; + + comptime { + usb.validate_device(@This()); + } + const vtable: usb.DeviceInterface.VTable = .{ .ep_writev = ep_writev, .ep_readv = ep_readv, @@ -186,13 +193,13 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { // EP0 is required; open OUT then IN (or vice versa), we will share buffer. self.interface.ep_open(&.{ .endpoint = .out(.ep0), - .max_packet_size = .from(64), + .max_packet_size = .from(device_capabilities.max_packet_size0), .attributes = .{ .transfer_type = .Control, .usage = .data }, .interval = 0, }); self.interface.ep_open(&.{ .endpoint = .in(.ep0), - .max_packet_size = .from(64), + .max_packet_size = .from(device_capabilities.max_packet_size0), .attributes = .{ .transfer_type = .Control, .usage = .data }, .interval = 0, }); diff --git a/port/wch/ch32v/src/hals/usbhs.zig b/port/wch/ch32v/src/hals/usbhs.zig index ec13ba575..d87593ff0 100644 --- a/port/wch/ch32v/src/hals/usbhs.zig +++ b/port/wch/ch32v/src/hals/usbhs.zig @@ -11,8 +11,6 @@ const usb = microzig.core.usb; const types = usb.types; const descriptor = usb.descriptor; -pub const max_packet_size: u11 = 512; - pub const USBHD_MAX_ENDPOINTS_COUNT = 16; const max_buffer_pool_size = USBHD_MAX_ENDPOINTS_COUNT * 2 * 512 + 64; @@ -141,6 +139,16 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { return struct { const Self = @This(); + pub const device_capabilities: usb.DeviceCapabilities = .{ + .max_supported_bcd_usb = .v2_00, + .max_packet_size0 = 64, + .max_packet_size = 512, + }; + + comptime { + usb.validate_device(@This()); + } + const vtable: usb.DeviceInterface.VTable = .{ .ep_writev = ep_writev, .ep_readv = ep_readv, @@ -171,13 +179,13 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { // EP0 is required; open OUT then IN (or vice versa), we will share buffer. self.interface.ep_open(&.{ .endpoint = .out(.ep0), - .max_packet_size = .from(64), + .max_packet_size = .from(device_capabilities.max_packet_size0), .attributes = .{ .transfer_type = .Control, .usage = .data }, .interval = 0, }); self.interface.ep_open(&.{ .endpoint = .in(.ep0), - .max_packet_size = .from(64), + .max_packet_size = .from(device_capabilities.max_packet_size0), .attributes = .{ .transfer_type = .Control, .usage = .data }, .interval = 0, }); From 89dd6bab1783f4c35066c98b15107651e342d0e9 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Wed, 11 Nov 2026 15:16:31 +0100 Subject: [PATCH 17/28] Revert unintended change --- port/nxp/mcx/build.zig.zon | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/port/nxp/mcx/build.zig.zon b/port/nxp/mcx/build.zig.zon index 2fb6ae318..0f6019884 100644 --- a/port/nxp/mcx/build.zig.zon +++ b/port/nxp/mcx/build.zig.zon @@ -4,11 +4,11 @@ .fingerprint = 0xe43e30911cb3fe37, .dependencies = .{ .@"microzig/build-internals" = .{ .path = "../../../build-internals" }, - // .@"mcux-soc-svd" = .{ - // .url = "https://github.com/nxp-mcuxpresso/mcux-soc-svd/archive/refs/tags/MCUX_2.16.100.tar.gz", - // .hash = "N-V-__8AADdFeofKFhsuzMbDdzLAKB4-syMJsHSEOTYGFrlH", - // .lazy = true, - // }, + .@"mcux-soc-svd" = .{ + .url = "https://github.com/nxp-mcuxpresso/mcux-soc-svd/archive/refs/tags/MCUX_2.16.100.tar.gz", + .hash = "N-V-__8AADdFeofKFhsuzMbDdzLAKB4-syMJsHSEOTYGFrlH", + .lazy = true, + }, }, .paths = .{ "build.zig", From 688ff290e8a187d156fba5bb7ec343ca5cf0a337 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Wed, 11 Nov 2026 18:03:57 +0100 Subject: [PATCH 18/28] Allow allocation of an type in usb devices --- core/src/core/usb.zig | 41 +++--- core/src/core/usb/configuration.zig | 161 +++++++++++----------- core/src/core/usb/drivers/CDC.zig | 2 +- core/src/core/usb/drivers/EchoExample.zig | 6 +- 4 files changed, 106 insertions(+), 104 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index 5de875552..b25132c12 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -70,13 +70,13 @@ pub const DeviceCapabilities = struct { /// Wraps a Descriptor type. Returned by the `create` method of the Descriptor. pub fn DriverInfo(Descriptor: type) type { return struct { + /// If not void, a pointer to a value of this type + /// will be passed to driver's init function. + Alloc: type = void, + /// Field attributes of `Alloc` + alloc_attrs: std.builtin.Type.Struct.FieldAttributes = .{}, Runtime: type, descriptor: Descriptor, - /// If not null, a slice of this length will be passed - /// to driver's init function. - alloc_bytes: ?usize = null, - /// Null means natural alignment - alloc_align: ?usize = null, }; } @@ -255,11 +255,7 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { const configurations = descriptor_parse_result.configurations; const config_descriptor = configurations[0].Descriptor{}; - const handlers_itf = configurations[0].handlers_itf; - const handlers_ep = configurations[0].HandlersEp{}; - const drivers_ep = configurations[0].drivers_ep; - const DriverAlloc = configurations[0].DriverAlloc; - const RuntimeData = configurations[0].RuntimeData; + const endpoint2handler = configurations[0].EndpointHandlers{}; /// If not zero, change the device address at the next opportunity. /// Necessary because when the host sets the device address, @@ -270,9 +266,9 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { /// Ep0 data waiting to be sent tx_slice: ?[]const u8, /// Driver state - driver_data: ?RuntimeData, + driver_data: ?configurations[0].RuntimeData, /// Additional driver allocations (size is comptime-known) - driver_alloc: DriverAlloc, + driver_alloc: configurations[0].DriverAlloc, /// Initial values pub const init: @This() = .{ @@ -285,7 +281,7 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { /// Returns a pointer to the drivers /// or null in case host has not yet configured the device. - pub fn drivers(self: *@This()) ?*RuntimeData { + pub fn drivers(self: *@This()) ?*configurations[0].RuntimeData { return if (self.driver_data) |*ret| ret else null; } @@ -314,8 +310,8 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { pub fn on_buffer(self: *@This(), device_itf: *DeviceInterface, comptime ep: types.Endpoint) void { log.debug("on_buffer {t} {t}", .{ ep.num, ep.dir }); - const driver_opt = comptime drivers_ep[@backingInt(ep.dir)][@backingInt(ep.num)]; - const handler = comptime @field(handlers_ep, @tagName(ep.dir))[@backingInt(ep.num)]; + const driver = comptime configurations[0].endpoint2driver[@backingInt(ep.dir)][@backingInt(ep.num)]; + const handler = comptime @field(endpoint2handler, @tagName(ep.dir))[@backingInt(ep.num)]; if (comptime ep == types.Endpoint.in(.ep0)) { // We use this opportunity to finish the delayed @@ -343,9 +339,8 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { } else if (comptime ep == types.Endpoint.out(.ep0)) log.warn("Unhandled packet on ep0 Out", .{}); - if (comptime driver_opt) |driver| { + if (comptime driver.len != 0) handler(&@field(self.driver_data.?, driver), ep.num); - } } /// Called by the device implementation on bus reset. @@ -399,12 +394,12 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { fn process_interface_setup(self: *@This(), setup: *const types.SetupPacket) ?[]const u8 { const itf_num: u8 = @truncate(setup.index.native()); + const num_interfaces = configurations[0].interface2driver.len; switch (itf_num) { - inline else => |itf| if (comptime itf < handlers_itf.len) { - const drv = handlers_itf[itf]; - return @field(self.driver_data.?, drv).class_request(setup); - } else { - log.warn("Interface index ({}) out of range ({})", .{ itf_num, handlers_itf.len }); + inline else => |itf| if (comptime itf < num_interfaces) + return @field(self.driver_data.?, configurations[0].interface2driver[itf]).class_request(setup) + else { + log.warn("Interface index ({}) out of range ({})", .{ itf_num, num_interfaces }); return nak; }, } @@ -444,7 +439,7 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { self.driver_data = null else { // We support just one config for now so ignore config index - self.driver_data = @as(RuntimeData, undefined); + self.driver_data = @as(configurations[0].RuntimeData, undefined); configurations[0].init(device_itf, &self.driver_data.?, &self.driver_alloc, config_descriptor); } } diff --git a/core/src/core/usb/configuration.zig b/core/src/core/usb/configuration.zig index 78dbe2f21..86d1be936 100644 --- a/core/src/core/usb/configuration.zig +++ b/core/src/core/usb/configuration.zig @@ -3,7 +3,6 @@ const usb = @import("../usb.zig"); const assert = std.debug.assert; const descriptor = usb.descriptor; -const types = usb.types; pub const Options = struct { attributes: descriptor.Configuration.Attributes, @@ -19,112 +18,133 @@ pub fn Create( options: Options, driver_config: anytype, ) type { + // Descriptor and EndpointHandlers are passed the default value of a struct, + // because zig does not support `anytype` in structs. return struct { const DriverName = []const u8; Descriptor: type, DriverAlloc: type, - drivers_ep: [2][16]?DriverName, - HandlersEp: type, - handlers_itf: []const DriverName, RuntimeData: type, + endpoint2driver: [2][16]DriverName, + EndpointHandlers: type, + interface2driver: []const DriverName, + pub fn create(device_capabilities: usb.DeviceCapabilities, strings: []const []const u8) struct { @This(), []const []const u8 } { var alloc = usb.DescriptorAllocator.init(options.unique_endpoints, strings); const configuration_s = alloc.string(options.name); - const driver_info = @typeInfo(@TypeOf(driver_config)).@"struct"; - const driver_field_names = driver_info.field_names; + const driver_names = @typeInfo(@TypeOf(driver_config)).@"struct".field_names; + + var endpoint2driver: [2][16]DriverName = @splat(@splat("")); + var interface2driver: []const DriverName = &.{}; + + // RuntimeData + var runtime_field_types: [driver_names.len]type = undefined; + + // Descriptor + var desc_field_types: [driver_names.len]type = undefined; + var desc_field_attrs: [driver_names.len]std.builtin.Type.Struct.FieldAttributes = undefined; - var desc_field_types: [driver_field_names.len]type = undefined; - var runtime_field_types: [driver_field_names.len]type = undefined; - var field_attrs: [driver_field_names.len]std.builtin.Type.Struct.FieldAttributes = undefined; + // EndpointHandlers var ep_handler_types: [2][16]type = @splat(@splat(void)); var ep_handler_names: [2][16][:0]const u8 = undefined; - var ep_handler_drivers: [2][16]?usize = @splat(@splat(null)); - var handlers_itf: []const DriverName = &.{}; - var driver_alloc_names: []const [:0]const u8 = &.{}; - var driver_alloc_types: []const type = &.{}; - var driver_alloc_attrs: []const std.builtin.Type.Struct.FieldAttributes = &.{}; - for (driver_field_names, driver_info.field_types, 0..) |driver_field_name, DriverType, drv_id| { - const drv = @field(driver_config, driver_field_name); + // DriverAlloc + var driver_alloc_types: [driver_names.len]type = undefined; + var driver_alloc_attrs: [driver_names.len]std.builtin.Type.Struct.FieldAttributes = undefined; + for ( + driver_names, + &runtime_field_types, + &desc_field_types, + &desc_field_attrs, + &driver_alloc_types, + &driver_alloc_attrs, + ) | + driver_field_name, + *Runtime, + *Descriptor, + *desc_attr, + *driver_alloc_type, + *driver_alloc_attr, + | { // Get type information for the current driver - const info = drv.driver_info(device_capabilities, &alloc); - const Descriptor = @TypeOf(info.descriptor); - runtime_field_types[drv_id] = info.Runtime; - - // If the driver requests memory, then collect the names, types, and attrs - if (info.alloc_bytes) |len| { - driver_alloc_names = driver_alloc_names ++ &[_][:0]const u8{driver_field_name}; - driver_alloc_types = driver_alloc_types ++ &[_]type{[len]u8}; - driver_alloc_attrs = driver_alloc_attrs ++ &[_]std.builtin.Type.Struct.FieldAttributes{.{ .@"align" = info.alloc_align }}; - } else { - assert(info.alloc_align == null); - } - - assert(@alignOf(Descriptor) == 1); + const drv = @field(driver_config, driver_field_name); + const driver_data = drv.driver_info(device_capabilities, &alloc); + Descriptor.* = @TypeOf(driver_data.descriptor); + assert(@alignOf(Descriptor.*) == 1); + Runtime.* = driver_data.Runtime; + desc_attr.* = .{ .default_value_ptr = &driver_data.descriptor }; + driver_alloc_type.* = driver_data.Alloc; + driver_alloc_attr.* = driver_data.alloc_attrs; // Collect handler types, names, and drivers, to later be bound to the appropriate // endpoints - const desc_info = @typeInfo(Descriptor).@"struct"; - for (desc_info.field_names, desc_info.field_types, 0..) |field_name, field_type, desc_num| { - const desc = @field(info.descriptor, field_name); + const desc_info = @typeInfo(Descriptor.*).@"struct"; + for (desc_info.field_names, desc_info.field_types, 0..) |desc_field_name, DescriptorField, desc_num| { + const desc = @field(driver_data.descriptor, desc_field_name); // Determine which interface numbers this driver owns. If it is an // InterfaceAssociation, then use the interface count. If it is an Interface, // then the driver owns just that one interface. if (desc_num == 0) { - const itf_start, const itf_count = switch (field_type) { + const itf_start, const itf_count = switch (DescriptorField) { descriptor.InterfaceAssociation => .{ desc.first_interface, desc.interface_count }, descriptor.Interface => .{ desc.interface_number, 1 }, else => |T| @compileError( "Expected first descriptor of driver " ++ - @typeName(DriverType) ++ + @typeName(@TypeOf(drv)) ++ " to be of type Interface or InterfaceAssociation descriptor, got: " ++ @typeName(T), ), }; - if (itf_start != handlers_itf.len) + if (itf_start != interface2driver.len) @compileError("interface numbering mismatch"); - handlers_itf = handlers_itf ++ @as([itf_count]DriverName, @splat(driver_field_name)); + interface2driver = interface2driver ++ @as([itf_count]DriverName, @splat(driver_field_name)); } - switch (field_type) { + switch (DescriptorField) { // Register handler for endpoints descriptor.Endpoint => { const ep_dir = @backingInt(desc.endpoint.dir); const ep_num = @backingInt(desc.endpoint.num); - if (ep_handler_types[ep_dir][ep_num] != void) + if (endpoint2driver[ep_dir][ep_num].len != 0) @compileError(std.fmt.comptimePrint( "ep{} {t}: multiple handlers: {s} and {s}", - .{ ep_num, desc.endpoint.dir, ep_handler_drivers[ep_dir][ep_num], driver_field_name }, + .{ ep_num, desc.endpoint.dir, endpoint2driver[ep_dir][ep_num], driver_field_name }, )); - ep_handler_types[ep_dir][ep_num] = usb.EndpointHandler(runtime_field_types[drv_id]); - ep_handler_drivers[ep_dir][ep_num] = drv_id; - ep_handler_names[ep_dir][ep_num] = field_name; + endpoint2driver[ep_dir][ep_num] = driver_field_name; + ep_handler_names[ep_dir][ep_num] = desc_field_name; + ep_handler_types[ep_dir][ep_num] = usb.EndpointHandler(Runtime.*); }, // Interface association must be first descriptor.InterfaceAssociation => assert(desc_num == 0), else => {}, } } - desc_field_types[drv_id] = Descriptor; - field_attrs[drv_id] = .{ .default_value_ptr = &info.descriptor }; } + const RuntimeData = @Struct( + .auto, + null, + driver_names, + &runtime_field_types, + &@splat(.{}), + ); + // Finally, bind the handler functions based on the data collected above. // Create a tuple with the appropriate types const ep_handlers_types: [2]type = .{ @Tuple(&ep_handler_types[0]), @Tuple(&ep_handler_types[1]) }; var ep_handlers: @Tuple(&ep_handlers_types) = undefined; // Iterate over all IN and OUT endpoints and bind the handler for any that are set. - for (&ep_handler_types, &ep_handler_names, &ep_handler_drivers, 0..) |htypes, hnames, hdrivers, dir| { - for (&htypes, &hnames, &hdrivers, 0..) |T, name, drv_id, ep| { - if (T != void) - ep_handlers[dir][ep] = @field(runtime_field_types[drv_id.?].handlers, name); + for (&ep_handlers, &ep_handler_names, &ep_handler_types, &endpoint2driver) |*handlers, *names, *types, *drivers| { + for (handlers, names, types, drivers) |*handler, name, Type, driver| { + if (Type != void) + handler.* = @field(@FieldType(RuntimeData, driver).handlers, name); } } @@ -135,9 +155,9 @@ pub fn Create( const DriverConfig = @Struct( .@"extern", null, - driver_field_names, + driver_names, &desc_field_types, - &field_attrs, + &desc_field_attrs, ); const Descriptor = extern struct { @@ -157,39 +177,25 @@ pub fn Create( @sizeOf(Descriptor), ) catch unreachable; - const idx_in = @backingInt(types.Dir.in); - const idx_out = @backingInt(types.Dir.out); + const idx_in = @backingInt(usb.types.Dir.in); + const idx_out = @backingInt(usb.types.Dir.out); return .{ .{ .Descriptor = Descriptor, .DriverAlloc = @Struct( .auto, null, - driver_alloc_names, - driver_alloc_types[0..driver_alloc_attrs.len], - driver_alloc_attrs[0..driver_alloc_attrs.len], + driver_names, + &driver_alloc_types, + &driver_alloc_attrs, ), - .drivers_ep = blk: { - var ret: @FieldType(@This(), "drivers_ep") = undefined; - for (&ret, ep_handler_drivers) |*dstv, srcv| { - for (dstv, srcv) |*dst, src_opt| { - dst.* = if (src_opt) |src| driver_field_names[src] else null; - } - } - break :blk ret; - }, - .HandlersEp = struct { + .endpoint2driver = endpoint2driver, + .EndpointHandlers = struct { in: ep_handlers_types[idx_in] = const_ep_handlers[idx_in], out: ep_handlers_types[idx_out] = const_ep_handlers[idx_out], }, - .handlers_itf = handlers_itf, - .RuntimeData = @Struct( - .auto, - null, - driver_field_names, - &runtime_field_types, - &@splat(.{}), - ), + .interface2driver = interface2driver, + .RuntimeData = RuntimeData, }, const_alloc.strings, }; @@ -209,9 +215,10 @@ pub fn Create( const drv = @field(driver_config, driver_field_name); const runtime = &@field(driver_data, driver_field_name); - // Don't pass empty slices around - if (@hasField(@TypeOf(driver_alloc.*), driver_field_name)) - runtime.init(drv, &cfg, device_itf, &@field(driver_alloc, driver_field_name)) + const alloc = &@field(driver_alloc, driver_field_name); + // Don't pass *void around + if (@TypeOf(alloc) != *void) + runtime.init(drv, &cfg, device_itf, alloc) else runtime.init(drv, &cfg, device_itf); diff --git a/core/src/core/usb/drivers/CDC.zig b/core/src/core/usb/drivers/CDC.zig index b60de5bed..cdb2ada01 100644 --- a/core/src/core/usb/drivers/CDC.zig +++ b/core/src/core/usb/drivers/CDC.zig @@ -233,7 +233,7 @@ pub fn driver_info( const itf_data = alloc.next_itf(); return .{ .Runtime = Runtime, - .alloc_bytes = 2 * device_capabilities.max_packet_size, + .Alloc = [2 * device_capabilities.max_packet_size]u8, .descriptor = .{ .itf_assoc = .{ .first_interface = itf_notifi, diff --git a/core/src/core/usb/drivers/EchoExample.zig b/core/src/core/usb/drivers/EchoExample.zig index eb8e242b4..4ce56b948 100644 --- a/core/src/core/usb/drivers/EchoExample.zig +++ b/core/src/core/usb/drivers/EchoExample.zig @@ -129,6 +129,9 @@ pub fn driver_info( alloc: *usb.DescriptorAllocator, ) usb.DriverInfo(Descriptor) { return .{ + // Buffers whose length is only known after creating the + // descriptor can be allocated at this stage. + .Alloc = [device_capabilities.max_packet_size]u8, .Runtime = Runtime, .descriptor = .{ .itf = .{ @@ -141,8 +144,5 @@ pub fn driver_info( .ep_out = .bulk(alloc.next_ep(.out), device_capabilities.max_packet_size), .ep_in = .bulk(alloc.next_ep(.in), device_capabilities.max_packet_size), }, - // Buffers whose length is only known after creating the - // descriptor can be allocated at this stage. - .alloc_bytes = device_capabilities.max_packet_size, }; } From 3253d5f67369d5b3543fdb791cfae0fd0303416e Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Wed, 11 Nov 2026 18:22:49 +0100 Subject: [PATCH 19/28] Introduce usb.HID_report --- core/src/core/usb.zig | 1 + core/src/core/usb/HID_report.zig | 365 ++++++++++++++++++++ core/src/core/usb/drivers/HID.zig | 293 +--------------- examples/nordic/nrf5x/src/usb_hid.zig | 82 +---- examples/raspberrypi/rp2xxx/src/usb_hid.zig | 82 +---- 5 files changed, 380 insertions(+), 443 deletions(-) create mode 100644 core/src/core/usb/HID_report.zig diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index b25132c12..b520d5b03 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -9,6 +9,7 @@ pub const drivers = struct { pub const EchoExample = @import("usb/drivers/EchoExample.zig"); pub const HID_Interrupt = @import("usb/drivers/HID.zig"); }; +pub const HID_report = @import("usb/HID_report.zig"); pub const types = @import("usb/types.zig"); pub const ack: []const u8 = ""; diff --git a/core/src/core/usb/HID_report.zig b/core/src/core/usb/HID_report.zig new file mode 100644 index 000000000..03833580a --- /dev/null +++ b/core/src/core/usb/HID_report.zig @@ -0,0 +1,365 @@ +const std = @import("std"); +const usb = @import("../usb.zig"); +const assert = std.debug.assert; + +/// Reports are a list of tagged ?i32 values. Encoding is variable-length. +pub const Item = union(enum) { + pub const Header = packed struct(u8) { + pub const Payload = enum(u2) { + null = 0, + i8 = 1, + i16 = 2, + i32 = 3, + }; + pub const Type = enum(u2) { main = 0, global = 1, local = 2, _ }; + + len: Payload, + type: Type, + tag: u4, + }; + + pub const Collection = enum(i32) { + Physical = 0, + Application, + Logical, + Report, + NamedArray, + UsageSwitch, + UsageModifier, + _, + }; + + pub const UsagePage = enum(i32) { + generic_desktop = 0x01, + keyboard = 0x07, + led = 0x08, + fido = @as(i16, @bitCast(@as(u16, 0xF1D0))), + vendor = 0xFF, + _, + }; + + pub const Usage = union(UsagePage) { + pub const GenericDesktop = enum(i32) { + keyboard = 0x06, + _, + }; + + pub const Keyboard = enum(i32) { _ }; + pub const Led = enum(i32) { _ }; + pub const Button = enum(i32) { _ }; + + pub const Fido = enum(i32) { + u2fhid = 0x01, + data_in = 0x20, + data_out = 0x21, + _, + }; + + generic_desktop: GenericDesktop, + keyboard: Keyboard, + led: Led, + fido: Fido, + vendor: i32, + + pub fn local(self: @This()) i32 { + return switch (self) { + inline else => |x| @backingInt(x), + .vendor => |x| x, + }; + } + }; + + pub const InputOutput = packed struct(i8) { + constant: bool = false, // HID_DATA/HID_CONSTANT + variable: bool = false, // HID_ARRAY/HID_VARIABLE + relative: bool = false, // HID_ABSOLUTE/HID_RELATIVE + wrap: bool = false, // HID_WRAP_NO/HID_WRAP + nonlinear: bool = false, // HID_LINEAR/HID_NONLINEAR + not_preferred: bool = false, // HID_PREFERRED_STATE/HID_PREFERRED_NO + null_state: bool = false, // HID_NO_NULL_POSITION/HID_NULL_STATE + @"volatile": bool = false, // HID_NON_VOLATILE/HID_VOLATILE + + pub const dynamic: @This() = .{ .variable = true }; + pub const selector: @This() = .{}; + pub const static: @This() = .{ .constant = true }; + }; + + pub const Data = struct { + pub const Type = enum { dynamic, selector }; + + usage: union(enum) { + global_page: UsagePage, + local: Usage, + local_raw: i32, + + pub fn report(self: @This()) Item { + return switch (self) { + .global_page => |page| .{ .global_usage_page = page }, + .local => |usage| .local_usage_enum(usage), + .local_raw => |val| .{ .local_usage = val }, + }; + } + }, + usage_range: ?[2]i32 = null, + logical_range: ?[2]i32 = null, + count: u31, + Child: type, + dir: usb.types.Dir, + type: Type, + }; + + // main items + main_input: InputOutput, + main_output: InputOutput, + main_collection: Collection, + main_feature: ?i32, + main_collection_end, + + // global items + global_usage_page: UsagePage, + global_logical_min: i32, + global_logical_max: i32, + global_physical_min: ?i32, + global_physical_max: ?i32, + global_unit_exponent: ?i32, + global_unit: ?i32, + global_report_size: u31, + global_report_id: u31, + global_report_count: u31, + global_push: ?i32, + global_pop: ?i32, + + // local items + local_usage: i32, + local_usage_min: i32, + local_usage_max: i32, + local_designator_index: ?i32, + local_designator_min: ?i32, + local_designator_max: ?i32, + local_string_index: ?i32, + local_string_min: ?i32, + local_string_max: ?i32, + local_delimiter, + + // helpers + usage_page_and_local: Usage, + global_logical_range: [2]i32, + global_report_type: type, + local_usage_range: [2]i32, + data: Data, + data_static: struct { usb.types.Dir, type }, + + pub fn main_io(dir: usb.types.Dir, payload: InputOutput) @This() { + return switch (dir) { + .in => .{ .main_input = payload }, + .out => .{ .main_output = payload }, + }; + } + + pub fn local_usage_enum(usage: Usage) @This() { + return .{ .local_usage = usage.local() }; + } + + pub fn encode_int(int_opt: ?i32) []const u8 { + const asBytes = std.mem.asBytes; + const toLittle = std.mem.nativeToLittle; + const int = int_opt orelse return ""; + return if (std.math.cast(i8, int)) |result| + &.{@bitCast(result)} + else if (std.math.cast(i16, int)) |result| + asBytes(&toLittle(i16, result)) + else + asBytes(&toLittle(i32, int)); + } + + pub fn header(self: @This(), length: usize) ?Header { + const len: Header.Payload = switch (length) { + 0 => .null, + 1 => .i8, + 2 => .i16, + 4 => .i32, + else => unreachable, + }; + const typ: Header.Type, const tag: u4 = switch (self) { + .main_input => .{ .main, 8 }, + .main_output => .{ .main, 9 }, + .main_collection => .{ .main, 10 }, + .main_feature => .{ .main, 11 }, + .main_collection_end => .{ .main, 12 }, + .global_usage_page => .{ .global, 0 }, + .global_logical_min => .{ .global, 1 }, + .global_logical_max => .{ .global, 2 }, + .global_physical_min => .{ .global, 3 }, + .global_physical_max => .{ .global, 4 }, + .global_unit_exponent => .{ .global, 5 }, + .global_unit => .{ .global, 6 }, + .global_report_size => .{ .global, 7 }, + .global_report_id => .{ .global, 8 }, + .global_report_count => .{ .global, 9 }, + .global_push => .{ .global, 10 }, + .global_pop => .{ .global, 11 }, + .local_usage => .{ .local, 0 }, + .local_usage_min => .{ .local, 1 }, + .local_usage_max => .{ .local, 2 }, + .local_designator_index => .{ .local, 3 }, + .local_designator_min => .{ .local, 4 }, + .local_designator_max => .{ .local, 5 }, + .local_string_index => .{ .local, 7 }, + .local_string_min => .{ .local, 8 }, + .local_string_max => .{ .local, 9 }, + .local_delimiter => .{ .local, 10 }, + else => return null, + }; + return .{ .len = len, .type = typ, .tag = tag }; + } + + pub fn type_size(T: type) comptime_int { + return switch (@typeInfo(T)) { + .int, .bool => @bitSizeOf(T), + else => @compileError(@typeName(T) ++ " cannot be sent in a HID report"), + }; + } + + pub fn create_report(items: []const @This()) []const u8 { + var ret: []const u8 = ""; + + for (items) |it| { + ret = ret ++ switch (it) { + .global_report_type => |T| blk: { + const count, const Child = switch (@typeInfo(T)) { + .array => |info| .{ info.len, info.child }, + else => .{ 1, T }, + }; + break :blk create_report(&.{ + .{ .global_report_count = count }, + .{ .global_report_size = type_size(Child) }, + }); + }, + .global_logical_range => |range| blk: { + assert(range[0] < range[1]); + break :blk create_report(&.{ + .{ .global_logical_min = range[0] }, + .{ .global_logical_max = range[1] }, + }); + }, + .local_usage_range => |range| blk: { + assert(range[0] < range[1]); + break :blk create_report(&.{ + .{ .local_usage_min = range[0] }, + .{ .local_usage_max = range[1] }, + }); + }, + .data => |info| create_report(&.{ + info.usage.report(), + if (info.usage_range) |ur| .{ .local_usage_range = ur } else null, + .{ .global_logical_range = info.logical_range orelse + switch (@typeInfo(info.Child)) { + .bool => .{ 0, 1 }, + .int => .{ std.math.minInt(info.Child), std.math.maxInt(info.Child) }, + else => unreachable, + } }, + .{ .global_report_type = [info.count]info.Child }, + .main_io(info.dir, switch (info.type) { + .dynamic => .dynamic, + .selector => .selector, + }), + }), + .data_static => |info| create_report(&.{ + .{ .global_report_type = info[1] }, + .main_io(info[0], .static), + }), + .usage_page_and_local => |usage| create_report(&.{ + .{ .global_usage_page = usage }, + .{ .local_usage = usage.local() }, + }), + inline else => |payload| blk: { + const data: []const u8 = switch (@TypeOf(payload)) { + void => "", + Collection, UsagePage => encode_int(@backingInt(payload)), + u31, i32, ?i32 => encode_int(payload), + InputOutput => &.{@bitCast(payload)}, + else => |T| @compileError(@typeName(T) ++ " cannot be turned into a HID report"), + }; + const h = it.header(data.len) orelse + @compileError(@tagName(it) ++ " is not a report"); + break :blk &[1]u8{@bitCast(h)} ++ data; + }, + }; + } + + return ret; + } +}; + +pub const BootKeyboardModifiers = packed struct(u8) { + lctrl: bool, + lshift: bool, + lalt: bool, + lgui: bool, + rctrl: bool, + rshift: bool, + ralt: bool, + rgui: bool, + + pub const none: @This() = @bitCast(@as(u8, 0)); +}; + +pub const BootKeycode = enum(u8) { + // Codes taken from https://gist.github.com/mildsunrise/4e231346e2078f440969cdefb6d4caa3 + // zig fmt: off + reserved = 0x00, error_roll_over, post_fail, error_undefined, + a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, + top_1, top_2, top_3, top_4, top_5, top_6, top_7, top_8, top_9, top_0, + enter, escape, delete, tab, space, + @"-", @"=", @"[", @"]", @"\\", @"non_us_#", @";", @"'", @"`", @",", @".", @"/", + caps_lock, + f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, + print_screen, scroll_lock, pause, insert, home, page_up, delete_forward, end, page_down, + right_arrow, left_arrow, down_arrow, up_arrow, num_lock, + kpad_div, kpad_mul, kpad_sub, kpad_add, kpad_enter, + kpad_1, kpad_2, kpad_3, kpad_4, kpad_5, kpad_6, kpad_7, kpad_8, kpad_9, kpad_0, + kpad_delete, @"non_us_\\", application, power, @"kpad_=", + f13, f14, f15, f16, f17, f18, f19, f20, f21, f22, f23, f24, + lctrl = 224, lshift, lalt, lgui, rctrl, rshift, ralt, rgui, + // zig fmt: on + _, +}; + +pub const boot_keyboard = [_]Item{ + .{ .global_usage_page = .generic_desktop }, + .local_usage_enum(.{ .generic_desktop = .keyboard }), + .{ .main_collection = .Application }, + // Input: modifier key bitmap + .{ .data = .{ + .usage = .{ .global_page = .keyboard }, + .usage_range = .{ 0xE0, 0xE7 }, + .count = 8, + .Child = bool, + .dir = .in, + .type = .dynamic, + } }, + // Reserved 8 bits + .{ .data_static = .{ .in, u8 } }, + // Output: indicator LEDs + .{ .data = .{ + .usage = .{ .global_page = .led }, + .usage_range = .{ 1, 5 }, + .count = 5, + .Child = bool, + .dir = .out, + .type = .dynamic, + } }, + // Padding + .{ .data_static = .{ .out, u3 } }, + // Input: up to 6 pressed key codes + .{ .data = .{ + .usage = .{ .global_page = .keyboard }, + .usage_range = .{ 0x00, 0xff }, + .count = 6, + .Child = u8, + .dir = .in, + .type = .selector, + } }, + // End + .main_collection_end, +}; diff --git a/core/src/core/usb/drivers/HID.zig b/core/src/core/usb/drivers/HID.zig index 6d1395f1d..2f835e679 100644 --- a/core/src/core/usb/drivers/HID.zig +++ b/core/src/core/usb/drivers/HID.zig @@ -5,295 +5,6 @@ const log = std.log.scoped(.usb_hid_int_driver); const Driver = @This(); -/// Reports are a list of tagged ?i32 values. Encoding is variable-length. -pub const ReportItem = union(enum) { - pub const Header = packed struct(u8) { - pub const Payload = enum(u2) { - null = 0, - i8 = 1, - i16 = 2, - i32 = 3, - }; - pub const Type = enum(u2) { main = 0, global = 1, local = 2, _ }; - - len: Payload, - type: Type, - tag: u4, - }; - - pub const Collection = enum(i32) { - Physical = 0, - Application, - Logical, - Report, - NamedArray, - UsageSwitch, - UsageModifier, - _, - }; - - pub const UsagePage = enum(i32) { - generic_desktop = 0x01, - keyboard = 0x07, - led = 0x08, - fido = @as(i16, @bitCast(@as(u16, 0xF1D0))), - vendor = 0xFF, - _, - }; - - pub const Usage = union(UsagePage) { - pub const GenericDesktop = enum(i32) { - keyboard = 0x06, - _, - }; - - pub const Keyboard = enum(i32) { _ }; - pub const Led = enum(i32) { _ }; - pub const Button = enum(i32) { _ }; - - pub const Fido = enum(i32) { - u2fhid = 0x01, - data_in = 0x20, - data_out = 0x21, - _, - }; - - generic_desktop: GenericDesktop, - keyboard: Keyboard, - led: Led, - fido: Fido, - vendor: i32, - - pub fn local(self: @This()) i32 { - return switch (self) { - inline else => |x| @backingInt(x), - .vendor => |x| x, - }; - } - }; - - pub const InputOutput = packed struct(i8) { - constant: bool = false, // HID_DATA/HID_CONSTANT - variable: bool = false, // HID_ARRAY/HID_VARIABLE - relative: bool = false, // HID_ABSOLUTE/HID_RELATIVE - wrap: bool = false, // HID_WRAP_NO/HID_WRAP - nonlinear: bool = false, // HID_LINEAR/HID_NONLINEAR - not_preferred: bool = false, // HID_PREFERRED_STATE/HID_PREFERRED_NO - null_state: bool = false, // HID_NO_NULL_POSITION/HID_NULL_STATE - @"volatile": bool = false, // HID_NON_VOLATILE/HID_VOLATILE - - pub const dynamic: @This() = .{ .variable = true }; - pub const selector: @This() = .{}; - pub const static: @This() = .{ .constant = true }; - }; - - pub const Data = struct { - pub const Type = enum { dynamic, selector }; - - usage: union(enum) { - global_page: UsagePage, - local: Usage, - local_raw: i32, - - pub fn report(self: @This()) ReportItem { - return switch (self) { - .global_page => |page| .{ .global_usage_page = page }, - .local => |usage| .local_usage_enum(usage), - .local_raw => |val| .{ .local_usage = val }, - }; - } - }, - usage_range: ?[2]i32 = null, - logical_range: ?[2]i32 = null, - count: u31, - Child: type, - dir: usb.types.Dir, - type: Type, - }; - - // main items - main_input: InputOutput, - main_output: InputOutput, - main_collection: Collection, - main_feature: ?i32, - main_collection_end, - - // global items - global_usage_page: UsagePage, - global_logical_min: i32, - global_logical_max: i32, - global_physical_min: ?i32, - global_physical_max: ?i32, - global_unit_exponent: ?i32, - global_unit: ?i32, - global_report_size: u31, - global_report_id: u31, - global_report_count: u31, - global_push: ?i32, - global_pop: ?i32, - - // local items - local_usage: i32, - local_usage_min: i32, - local_usage_max: i32, - local_designator_index: ?i32, - local_designator_min: ?i32, - local_designator_max: ?i32, - local_string_index: ?i32, - local_string_min: ?i32, - local_string_max: ?i32, - local_delimiter, - - // helpers - usage_page_and_local: Usage, - global_logical_range: [2]i32, - global_report_type: type, - local_usage_range: [2]i32, - data: Data, - data_static: struct { usb.types.Dir, type }, - - pub fn main_io(dir: usb.types.Dir, payload: InputOutput) @This() { - return switch (dir) { - .in => .{ .main_input = payload }, - .out => .{ .main_output = payload }, - }; - } - - pub fn local_usage_enum(usage: Usage) @This() { - return .{ .local_usage = usage.local() }; - } - - pub fn encode_int(int_opt: ?i32) []const u8 { - const asBytes = std.mem.asBytes; - const toLittle = std.mem.nativeToLittle; - const int = int_opt orelse return ""; - return if (std.math.cast(i8, int)) |result| - &.{@bitCast(result)} - else if (std.math.cast(i16, int)) |result| - asBytes(&toLittle(i16, result)) - else - asBytes(&toLittle(i32, int)); - } - - pub fn header(self: @This(), length: usize) ?Header { - const len: Header.Payload = switch (length) { - 0 => .null, - 1 => .i8, - 2 => .i16, - 4 => .i32, - else => unreachable, - }; - const typ: Header.Type, const tag: u4 = switch (self) { - .main_input => .{ .main, 8 }, - .main_output => .{ .main, 9 }, - .main_collection => .{ .main, 10 }, - .main_feature => .{ .main, 11 }, - .main_collection_end => .{ .main, 12 }, - .global_usage_page => .{ .global, 0 }, - .global_logical_min => .{ .global, 1 }, - .global_logical_max => .{ .global, 2 }, - .global_physical_min => .{ .global, 3 }, - .global_physical_max => .{ .global, 4 }, - .global_unit_exponent => .{ .global, 5 }, - .global_unit => .{ .global, 6 }, - .global_report_size => .{ .global, 7 }, - .global_report_id => .{ .global, 8 }, - .global_report_count => .{ .global, 9 }, - .global_push => .{ .global, 10 }, - .global_pop => .{ .global, 11 }, - .local_usage => .{ .local, 0 }, - .local_usage_min => .{ .local, 1 }, - .local_usage_max => .{ .local, 2 }, - .local_designator_index => .{ .local, 3 }, - .local_designator_min => .{ .local, 4 }, - .local_designator_max => .{ .local, 5 }, - .local_string_index => .{ .local, 7 }, - .local_string_min => .{ .local, 8 }, - .local_string_max => .{ .local, 9 }, - .local_delimiter => .{ .local, 10 }, - else => return null, - }; - return .{ .len = len, .type = typ, .tag = tag }; - } - - pub fn type_size(T: type) comptime_int { - return switch (@typeInfo(T)) { - .int, .bool => @bitSizeOf(T), - else => @compileError(@typeName(T) ++ " cannot be sent in a HID report"), - }; - } - - pub fn create_report(items: []const ?@This()) []const u8 { - var ret: []const u8 = ""; - - for (items) |it_opt| if (it_opt) |it| { - ret = ret ++ switch (it) { - .global_report_type => |T| blk: { - const count, const Child = switch (@typeInfo(T)) { - .array => |info| .{ info.len, info.child }, - else => .{ 1, T }, - }; - break :blk create_report(&.{ - .{ .global_report_count = count }, - .{ .global_report_size = type_size(Child) }, - }); - }, - .global_logical_range => |range| blk: { - assert(range[0] < range[1]); - break :blk create_report(&.{ - .{ .global_logical_min = range[0] }, - .{ .global_logical_max = range[1] }, - }); - }, - .local_usage_range => |range| blk: { - assert(range[0] < range[1]); - break :blk create_report(&.{ - .{ .local_usage_min = range[0] }, - .{ .local_usage_max = range[1] }, - }); - }, - .data => |info| create_report(&.{ - info.usage.report(), - if (info.usage_range) |ur| .{ .local_usage_range = ur } else null, - .{ .global_logical_range = info.logical_range orelse - switch (@typeInfo(info.Child)) { - .bool => .{ 0, 1 }, - .int => .{ std.math.minInt(info.Child), std.math.maxInt(info.Child) }, - else => unreachable, - } }, - .{ .global_report_type = [info.count]info.Child }, - .main_io(info.dir, switch (info.type) { - .dynamic => .dynamic, - .selector => .selector, - }), - }), - .data_static => |info| create_report(&.{ - .{ .global_report_type = info[1] }, - .main_io(info[0], .static), - }), - .usage_page_and_local => |usage| create_report(&.{ - .{ .global_usage_page = usage }, - .{ .local_usage = usage.local() }, - }), - inline else => |payload| blk: { - const data: []const u8 = switch (@TypeOf(payload)) { - void => "", - Collection, UsagePage => encode_int(@backingInt(payload)), - u31, i32, ?i32 => encode_int(payload), - InputOutput => &.{@bitCast(payload)}, - else => |T| @compileError(@typeName(T) ++ " cannot be turned into a HID report"), - }; - const h = it.header(data.len) orelse - @compileError(@tagName(it) ++ " is not a report"); - break :blk &[1]u8{@bitCast(h)} ++ data; - }, - }; - }; - - return ret; - } -}; - pub const Descriptor = extern struct { const desc = usb.descriptor; @@ -449,7 +160,7 @@ protocol: ClassCode.Protocol(), itf_string: []const u8 = "", poll_interval: u8, country_code: usb.descriptor.HID.CountryCode = .NotSupported, -report_descriptor: []const ?ReportItem, +report_descriptor: []const usb.HID_report.Item, InReport: type, OutReport: type, @@ -464,7 +175,7 @@ pub fn driver_info( .Runtime = Runtime( self.InReport, self.OutReport, - ReportItem.create_report(self.report_descriptor), + usb.HID_report.Item.create_report(self.report_descriptor), ), .descriptor = .{ .interface = .{ diff --git a/examples/nordic/nrf5x/src/usb_hid.zig b/examples/nordic/nrf5x/src/usb_hid.zig index c59f094fb..03944dc99 100644 --- a/examples/nordic/nrf5x/src/usb_hid.zig +++ b/examples/nordic/nrf5x/src/usb_hid.zig @@ -10,6 +10,7 @@ const time = nrf.time; const USBD = nrf.usbd.USBD; const clocks = nrf.clocks; const uart = nrf.uart.num(0); +const Keycode = usb.HID_report.BootKeycode; pub const panic = microzig.panic; @@ -27,44 +28,10 @@ comptime { _ = microzig.export_startup(); } -pub const Modifiers = packed struct(u8) { - lctrl: bool, - lshift: bool, - lalt: bool, - lgui: bool, - rctrl: bool, - rshift: bool, - ralt: bool, - rgui: bool, - - pub const none: @This() = @bitCast(@as(u8, 0)); -}; - -pub const Code = enum(u8) { - // Codes taken from https://gist.github.com/mildsunrise/4e231346e2078f440969cdefb6d4caa3 - // zig fmt: off - reserved = 0x00, error_roll_over, post_fail, error_undefined, - a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, - top_1, top_2, top_3, top_4, top_5, top_6, top_7, top_8, top_9, top_0, - enter, escape, delete, tab, space, - @"-", @"=", @"[", @"]", @"\\", @"non_us_#", @";", @"'", @"`", @",", @".", @"/", - caps_lock, - f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, - print_screen, scroll_lock, pause, insert, home, page_up, delete_forward, end, page_down, - right_arrow, left_arrow, down_arrow, up_arrow, num_lock, - kpad_div, kpad_mul, kpad_sub, kpad_add, kpad_enter, - kpad_1, kpad_2, kpad_3, kpad_4, kpad_5, kpad_6, kpad_7, kpad_8, kpad_9, kpad_0, - kpad_delete, @"non_us_\\", application, power, @"kpad_=", - f13, f14, f15, f16, f17, f18, f19, f20, f21, f22, f23, f24, - lctrl = 224, lshift, lalt, lgui, rctrl, rshift, ralt, rgui, - // zig fmt: on - _, -}; - pub const KeyboardInReport = extern struct { - modifiers: Modifiers, + modifiers: usb.HID_report.BootKeyboardModifiers, reserved: u8 = 0, - keys: [6]Code, + keys: [6]Keycode, comptime { std.debug.assert(@sizeOf(@This()) == 8); @@ -85,44 +52,7 @@ const hid_driver_options: usb.drivers.HID_Interrupt = .{ .protocol = .Boot, .itf_string = "Boot Keyboard", .poll_interval = 1, - .report_descriptor = &.{ - .{ .global_usage_page = .generic_desktop }, - .local_usage_enum(.{ .generic_desktop = .keyboard }), - .{ .main_collection = .Application }, - // Input: modifier key bitmap - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0xE0, 0xE7 }, - .count = 8, - .Child = bool, - .dir = .in, - .type = .dynamic, - } }, - // Reserved 8 bits - .{ .data_static = .{ .in, u8 } }, - // Output: indicator LEDs - .{ .data = .{ - .usage = .{ .global_page = .led }, - .usage_range = .{ 1, 5 }, - .count = 5, - .Child = bool, - .dir = .out, - .type = .dynamic, - } }, - // Padding - .{ .data_static = .{ .out, u3 } }, - // Input: up to 6 pressed key codes - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0x00, 0xff }, - .count = 6, - .Child = u8, - .dir = .in, - .type = .selector, - } }, - // End - .main_collection_end, - }, + .report_descriptor = &usb.HID_report.boot_keyboard, .InReport = KeyboardInReport, .OutReport = KeyboardOutReport, }; @@ -154,7 +84,7 @@ pub fn main() !void { var old: u64 = time.get_time_since_boot().to_us(); var new: u64 = 0; - const message: []const Code = &.{ .h, .e, .l, .l, .o, .space, .w, .o, .r, .l, .d, .caps_lock, .enter }; + const message: []const Keycode = &.{ .h, .e, .l, .l, .o, .space, .w, .o, .r, .l, .d, .caps_lock, .enter }; var idx: usize = 0; while (true) { @@ -170,7 +100,7 @@ pub fn main() !void { std.log.info("report {}", .{idx}); idx += @intFromBool(if (idx & 1 == 0 and idx < 2 * message.len) drivers.keyboard.send_report( - &.{ .modifiers = .none, .keys = .{message[@intCast(idx / 2)]} ++ @as([5]Code, @splat(.reserved)) }, + &.{ .modifiers = .none, .keys = .{message[@intCast(idx / 2)]} ++ @as([5]Keycode, @splat(.reserved)) }, ) else drivers.keyboard.send_report(&.empty)); diff --git a/examples/raspberrypi/rp2xxx/src/usb_hid.zig b/examples/raspberrypi/rp2xxx/src/usb_hid.zig index 111699520..c2b4c4767 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_hid.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_hid.zig @@ -5,6 +5,7 @@ const rp2xxx = microzig.hal; const time = rp2xxx.time; const usb = microzig.core.usb; const USB_Device = rp2xxx.usb.Polled(.{}); +const Keycode = usb.HID_report.BootKeycode; pub const std_options = microzig.std_options(.{ .log_level = .debug, @@ -20,44 +21,10 @@ comptime { _ = microzig.export_startup(); } -pub const Modifiers = packed struct(u8) { - lctrl: bool, - lshift: bool, - lalt: bool, - lgui: bool, - rctrl: bool, - rshift: bool, - ralt: bool, - rgui: bool, - - pub const none: @This() = @bitCast(@as(u8, 0)); -}; - -pub const Code = enum(u8) { - // Codes taken from https://gist.github.com/mildsunrise/4e231346e2078f440969cdefb6d4caa3 - // zig fmt: off - reserved = 0x00, error_roll_over, post_fail, error_undefined, - a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, - top_1, top_2, top_3, top_4, top_5, top_6, top_7, top_8, top_9, top_0, - enter, escape, delete, tab, space, - @"-", @"=", @"[", @"]", @"\\", @"non_us_#", @";", @"'", @"`", @",", @".", @"/", - caps_lock, - f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, - print_screen, scroll_lock, pause, insert, home, page_up, delete_forward, end, page_down, - right_arrow, left_arrow, down_arrow, up_arrow, num_lock, - kpad_div, kpad_mul, kpad_sub, kpad_add, kpad_enter, - kpad_1, kpad_2, kpad_3, kpad_4, kpad_5, kpad_6, kpad_7, kpad_8, kpad_9, kpad_0, - kpad_delete, @"non_us_\\", application, power, @"kpad_=", - f13, f14, f15, f16, f17, f18, f19, f20, f21, f22, f23, f24, - lctrl = 224, lshift, lalt, lgui, rctrl, rshift, ralt, rgui, - // zig fmt: on - _, -}; - pub const KeyboardInReport = extern struct { - modifiers: Modifiers, + modifiers: usb.HID_report.BootKeyboardModifiers, reserved: u8 = 0, - keys: [6]Code, + keys: [6]Keycode, comptime { std.debug.assert(@sizeOf(@This()) == 8); @@ -78,44 +45,7 @@ const hid_driver_options: usb.drivers.HID_Interrupt = .{ .protocol = .Boot, .itf_string = "Boot Keyboard", .poll_interval = 1, - .report_descriptor = &.{ - .{ .global_usage_page = .generic_desktop }, - .local_usage_enum(.{ .generic_desktop = .keyboard }), - .{ .main_collection = .Application }, - // Input: modifier key bitmap - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0xE0, 0xE7 }, - .count = 8, - .Child = bool, - .dir = .in, - .type = .dynamic, - } }, - // Reserved 8 bits - .{ .data_static = .{ .in, u8 } }, - // Output: indicator LEDs - .{ .data = .{ - .usage = .{ .global_page = .led }, - .usage_range = .{ 1, 5 }, - .count = 5, - .Child = bool, - .dir = .out, - .type = .dynamic, - } }, - // Padding - .{ .data_static = .{ .out, u3 } }, - // Input: up to 6 pressed key codes - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0x00, 0xff }, - .count = 6, - .Child = u8, - .dir = .in, - .type = .selector, - } }, - // End - .main_collection_end, - }, + .report_descriptor = &usb.HID_report.boot_keyboard, .InReport = KeyboardInReport, .OutReport = KeyboardOutReport, }; @@ -162,7 +92,7 @@ pub fn main() !void { var old: u64 = time.get_time_since_boot().to_us(); var new: u64 = 0; - const message: []const Code = &.{ .h, .e, .l, .l, .o, .space, .w, .o, .r, .l, .d, .caps_lock, .enter }; + const message: []const Keycode = &.{ .h, .e, .l, .l, .o, .space, .w, .o, .r, .l, .d, .caps_lock, .enter }; var idx: usize = 0; while (true) { @@ -177,7 +107,7 @@ pub fn main() !void { } else { idx += @intFromBool(if (idx & 1 == 0 and idx < 2 * message.len) drivers.keyboard.send_report( - &.{ .modifiers = .none, .keys = .{message[@intCast(idx / 2)]} ++ @as([5]Code, @splat(.reserved)) }, + &.{ .modifiers = .none, .keys = .{message[@intCast(idx / 2)]} ++ @as([5]Keycode, @splat(.reserved)) }, ) else drivers.keyboard.send_report(&.empty)); From a34e75c9f88f185f5e80053bca7a7e5feccaee48 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Wed, 11 Nov 2026 19:00:17 +0100 Subject: [PATCH 20/28] Fix bug in HID driver --- core/src/core/usb/drivers/HID.zig | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/core/src/core/usb/drivers/HID.zig b/core/src/core/usb/drivers/HID.zig index 2f835e679..94ca338e2 100644 --- a/core/src/core/usb/drivers/HID.zig +++ b/core/src/core/usb/drivers/HID.zig @@ -171,11 +171,12 @@ pub fn driver_info( ) usb.DriverInfo(Descriptor) { assert(@sizeOf(self.InReport) <= device_capabilities.max_packet_size); assert(@sizeOf(self.OutReport) <= device_capabilities.max_packet_size); + const report_descriptor = usb.HID_report.Item.create_report(self.report_descriptor); return .{ .Runtime = Runtime( self.InReport, self.OutReport, - usb.HID_report.Item.create_report(self.report_descriptor), + report_descriptor, ), .descriptor = .{ .interface = .{ @@ -188,7 +189,7 @@ pub fn driver_info( .hid = .{ .country_code = self.country_code, .num_descriptors = 1, - .report_length = .from(self.report_descriptor.len), + .report_length = .from(report_descriptor.len), }, .ep_out = .interrupt( alloc.next_ep(.out), From 8e99d8f82adc2cf69757d57d419bdaabf243e491 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Wed, 11 Nov 2026 19:11:20 +0100 Subject: [PATCH 21/28] Reduce use of @This() --- core/src/core/usb/drivers/CDC.zig | 2 +- core/src/core/usb/drivers/EchoExample.zig | 2 +- core/src/core/usb/drivers/HID.zig | 2 +- port/nordic/nrf5x/src/hal/usbd.zig | 6 +++--- port/wch/ch32v/src/hals/usbd.zig | 2 +- port/wch/ch32v/src/hals/usbfs.zig | 2 +- port/wch/ch32v/src/hals/usbhs.zig | 2 +- 7 files changed, 9 insertions(+), 9 deletions(-) diff --git a/core/src/core/usb/drivers/CDC.zig b/core/src/core/usb/drivers/CDC.zig index cdb2ada01..1b3724df5 100644 --- a/core/src/core/usb/drivers/CDC.zig +++ b/core/src/core/usb/drivers/CDC.zig @@ -223,7 +223,7 @@ itf_data_str: []const u8 = "", /// are used, this function is called for each, with different arguments. Passing arguments /// through this function is preferred to making the whole driver generic. pub fn driver_info( - self: @This(), + self: Driver, comptime device_capabilities: usb.DeviceCapabilities, alloc: *usb.DescriptorAllocator, ) usb.DriverInfo(Descriptor) { diff --git a/core/src/core/usb/drivers/EchoExample.zig b/core/src/core/usb/drivers/EchoExample.zig index 4ce56b948..c6c597433 100644 --- a/core/src/core/usb/drivers/EchoExample.zig +++ b/core/src/core/usb/drivers/EchoExample.zig @@ -124,7 +124,7 @@ itf_string: []const u8 = "", /// this function is called for each, with different arguments. /// Aside from the descriptor, this function can return a type that is later used pub fn driver_info( - self: @This(), + self: Driver, comptime device_capabilities: usb.DeviceCapabilities, alloc: *usb.DescriptorAllocator, ) usb.DriverInfo(Descriptor) { diff --git a/core/src/core/usb/drivers/HID.zig b/core/src/core/usb/drivers/HID.zig index 94ca338e2..341a81dfd 100644 --- a/core/src/core/usb/drivers/HID.zig +++ b/core/src/core/usb/drivers/HID.zig @@ -165,7 +165,7 @@ InReport: type, OutReport: type, pub fn driver_info( - comptime self: @This(), + comptime self: Driver, comptime device_capabilities: usb.DeviceCapabilities, alloc: *usb.DescriptorAllocator, ) usb.DriverInfo(Descriptor) { diff --git a/port/nordic/nrf5x/src/hal/usbd.zig b/port/nordic/nrf5x/src/hal/usbd.zig index 322ba829e..85d57e92b 100644 --- a/port/nordic/nrf5x/src/hal/usbd.zig +++ b/port/nordic/nrf5x/src/hal/usbd.zig @@ -40,6 +40,8 @@ const EP_Config = struct { }; pub const USBD = struct { + const Self = @This(); + power: PowerState = .detached, bufs_in: [NUM_EP][MAX_PACKET_SIZE]u8 align(4) = @splat(@splat(0)), @@ -59,7 +61,7 @@ pub const USBD = struct { }; comptime { - usb.validate_device(@This()); + usb.validate_device(Self); } const vtable: usb.DeviceInterface.VTable = .{ @@ -70,8 +72,6 @@ pub const USBD = struct { .set_address = set_address, }; - const Self = @This(); - pub fn init() Self { peripherals.USBD.USBPULLUP.write_raw(0); peripherals.USBD.ENABLE.write_raw(0); diff --git a/port/wch/ch32v/src/hals/usbd.zig b/port/wch/ch32v/src/hals/usbd.zig index b708f9167..fde747a00 100644 --- a/port/wch/ch32v/src/hals/usbd.zig +++ b/port/wch/ch32v/src/hals/usbd.zig @@ -334,7 +334,7 @@ pub fn Polled(comptime setup: Setup, comptime cfg: Config) type { }; comptime { - usb.validate_device(@This()); + usb.validate_device(Self); } const vtable: usb.DeviceInterface.VTable = .{ diff --git a/port/wch/ch32v/src/hals/usbfs.zig b/port/wch/ch32v/src/hals/usbfs.zig index bcdbde8f7..fdb7d3f77 100644 --- a/port/wch/ch32v/src/hals/usbfs.zig +++ b/port/wch/ch32v/src/hals/usbfs.zig @@ -160,7 +160,7 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { }; comptime { - usb.validate_device(@This()); + usb.validate_device(Self); } const vtable: usb.DeviceInterface.VTable = .{ diff --git a/port/wch/ch32v/src/hals/usbhs.zig b/port/wch/ch32v/src/hals/usbhs.zig index d87593ff0..c6c1077e4 100644 --- a/port/wch/ch32v/src/hals/usbhs.zig +++ b/port/wch/ch32v/src/hals/usbhs.zig @@ -146,7 +146,7 @@ pub fn Polled(comptime _: Setup, comptime cfg: Config) type { }; comptime { - usb.validate_device(@This()); + usb.validate_device(Self); } const vtable: usb.DeviceInterface.VTable = .{ From 77429ec074e9f5f50430d1968f1ff62304749cf6 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Thu, 12 Nov 2026 00:32:21 +0100 Subject: [PATCH 22/28] Automatic HID report struct generation --- core/src/core/usb/HID_report.zig | 376 +++++++++++--------- core/src/core/usb/drivers/HID.zig | 44 ++- examples/nordic/nrf5x/src/usb_hid.zig | 36 +- examples/raspberrypi/rp2xxx/src/usb_hid.zig | 38 +- 4 files changed, 248 insertions(+), 246 deletions(-) diff --git a/core/src/core/usb/HID_report.zig b/core/src/core/usb/HID_report.zig index 03833580a..5a018340c 100644 --- a/core/src/core/usb/HID_report.zig +++ b/core/src/core/usb/HID_report.zig @@ -1,6 +1,36 @@ const std = @import("std"); const usb = @import("../usb.zig"); const assert = std.debug.assert; +const SFAttributes = std.builtin.Type.Struct.FieldAttributes; + +pub const Keycode = enum(u8) { + // Codes taken from https://gist.github.com/mildsunrise/4e231346e2078f440969cdefb6d4caa3 + // zig fmt: off + reserved = 0x00, error_roll_over, post_fail, error_undefined, + a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, + top_1, top_2, top_3, top_4, top_5, top_6, top_7, top_8, top_9, top_0, + enter, escape, delete, tab, space, + @"-", @"=", @"[", @"]", @"\\", @"non_us_#", @";", @"'", @"`", @",", @".", @"/", + caps_lock, + f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, + print_screen, scroll_lock, pause, insert, home, page_up, delete_forward, end, page_down, + right_arrow, left_arrow, down_arrow, up_arrow, num_lock, + kpad_div, kpad_mul, kpad_sub, kpad_add, kpad_enter, + kpad_1, kpad_2, kpad_3, kpad_4, kpad_5, kpad_6, kpad_7, kpad_8, kpad_9, kpad_0, + kpad_delete, @"non_us_\\", application, power, @"kpad_=", + f13, f14, f15, f16, f17, f18, f19, f20, f21, f22, f23, f24, + lctrl = 224, lshift, lalt, lgui, rctrl, rshift, ralt, rgui, + // zig fmt: on + _, +}; + +pub const Ledcode = enum(u3) { + num_lock = 1, + caps_lock = 2, + scroll_lock = 3, + compose = 4, + kana = 5, +}; /// Reports are a list of tagged ?i32 values. Encoding is variable-length. pub const Item = union(enum) { @@ -36,6 +66,14 @@ pub const Item = union(enum) { fido = @as(i16, @bitCast(@as(u16, 0xF1D0))), vendor = 0xFF, _, + + pub fn Type(self: @This()) type { + return switch (self) { + .keyboard => Keycode, + .led => Ledcode, + inline else => @compileError("Not supported for: " ++ @tagName(self)), + }; + } }; pub const Usage = union(UsagePage) { @@ -84,30 +122,6 @@ pub const Item = union(enum) { pub const static: @This() = .{ .constant = true }; }; - pub const Data = struct { - pub const Type = enum { dynamic, selector }; - - usage: union(enum) { - global_page: UsagePage, - local: Usage, - local_raw: i32, - - pub fn report(self: @This()) Item { - return switch (self) { - .global_page => |page| .{ .global_usage_page = page }, - .local => |usage| .local_usage_enum(usage), - .local_raw => |val| .{ .local_usage = val }, - }; - } - }, - usage_range: ?[2]i32 = null, - logical_range: ?[2]i32 = null, - count: u31, - Child: type, - dir: usb.types.Dir, - type: Type, - }; - // main items main_input: InputOutput, main_output: InputOutput, @@ -141,14 +155,6 @@ pub const Item = union(enum) { local_string_max: ?i32, local_delimiter, - // helpers - usage_page_and_local: Usage, - global_logical_range: [2]i32, - global_report_type: type, - local_usage_range: [2]i32, - data: Data, - data_static: struct { usb.types.Dir, type }, - pub fn main_io(dir: usb.types.Dir, payload: InputOutput) @This() { return switch (dir) { .in => .{ .main_input = payload }, @@ -172,7 +178,7 @@ pub const Item = union(enum) { asBytes(&toLittle(i32, int)); } - pub fn header(self: @This(), length: usize) ?Header { + pub fn header(self: @This(), length: usize) Header { const len: Header.Payload = switch (length) { 0 => .null, 1 => .i8, @@ -208,81 +214,25 @@ pub const Item = union(enum) { .local_string_min => .{ .local, 8 }, .local_string_max => .{ .local, 9 }, .local_delimiter => .{ .local, 10 }, - else => return null, }; return .{ .len = len, .type = typ, .tag = tag }; } - pub fn type_size(T: type) comptime_int { - return switch (@typeInfo(T)) { - .int, .bool => @bitSizeOf(T), - else => @compileError(@typeName(T) ++ " cannot be sent in a HID report"), - }; - } - pub fn create_report(items: []const @This()) []const u8 { var ret: []const u8 = ""; for (items) |it| { ret = ret ++ switch (it) { - .global_report_type => |T| blk: { - const count, const Child = switch (@typeInfo(T)) { - .array => |info| .{ info.len, info.child }, - else => .{ 1, T }, - }; - break :blk create_report(&.{ - .{ .global_report_count = count }, - .{ .global_report_size = type_size(Child) }, - }); - }, - .global_logical_range => |range| blk: { - assert(range[0] < range[1]); - break :blk create_report(&.{ - .{ .global_logical_min = range[0] }, - .{ .global_logical_max = range[1] }, - }); - }, - .local_usage_range => |range| blk: { - assert(range[0] < range[1]); - break :blk create_report(&.{ - .{ .local_usage_min = range[0] }, - .{ .local_usage_max = range[1] }, - }); - }, - .data => |info| create_report(&.{ - info.usage.report(), - if (info.usage_range) |ur| .{ .local_usage_range = ur } else null, - .{ .global_logical_range = info.logical_range orelse - switch (@typeInfo(info.Child)) { - .bool => .{ 0, 1 }, - .int => .{ std.math.minInt(info.Child), std.math.maxInt(info.Child) }, - else => unreachable, - } }, - .{ .global_report_type = [info.count]info.Child }, - .main_io(info.dir, switch (info.type) { - .dynamic => .dynamic, - .selector => .selector, - }), - }), - .data_static => |info| create_report(&.{ - .{ .global_report_type = info[1] }, - .main_io(info[0], .static), - }), - .usage_page_and_local => |usage| create_report(&.{ - .{ .global_usage_page = usage }, - .{ .local_usage = usage.local() }, - }), inline else => |payload| blk: { const data: []const u8 = switch (@TypeOf(payload)) { void => "", Collection, UsagePage => encode_int(@backingInt(payload)), u31, i32, ?i32 => encode_int(payload), - InputOutput => &.{@bitCast(payload)}, + InputOutput => &.{@backingInt(payload)}, else => |T| @compileError(@typeName(T) ++ " cannot be turned into a HID report"), }; - const h = it.header(data.len) orelse - @compileError(@tagName(it) ++ " is not a report"); - break :blk &[1]u8{@bitCast(h)} ++ data; + const h = it.header(data.len); + break :blk &[1]u8{@backingInt(h)} ++ data; }, }; } @@ -291,75 +241,179 @@ pub const Item = union(enum) { } }; -pub const BootKeyboardModifiers = packed struct(u8) { - lctrl: bool, - lshift: bool, - lalt: bool, - lgui: bool, - rctrl: bool, - rshift: bool, - ralt: bool, - rgui: bool, - - pub const none: @This() = @bitCast(@as(u8, 0)); -}; +pub const Finalized = struct { + descriptor: []const u8, + in: type, + out: type, -pub const BootKeycode = enum(u8) { - // Codes taken from https://gist.github.com/mildsunrise/4e231346e2078f440969cdefb6d4caa3 - // zig fmt: off - reserved = 0x00, error_roll_over, post_fail, error_undefined, - a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, - top_1, top_2, top_3, top_4, top_5, top_6, top_7, top_8, top_9, top_0, - enter, escape, delete, tab, space, - @"-", @"=", @"[", @"]", @"\\", @"non_us_#", @";", @"'", @"`", @",", @".", @"/", - caps_lock, - f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, - print_screen, scroll_lock, pause, insert, home, page_up, delete_forward, end, page_down, - right_arrow, left_arrow, down_arrow, up_arrow, num_lock, - kpad_div, kpad_mul, kpad_sub, kpad_add, kpad_enter, - kpad_1, kpad_2, kpad_3, kpad_4, kpad_5, kpad_6, kpad_7, kpad_8, kpad_9, kpad_0, - kpad_delete, @"non_us_\\", application, power, @"kpad_=", - f13, f14, f15, f16, f17, f18, f19, f20, f21, f22, f23, f24, - lctrl = 224, lshift, lalt, lgui, rctrl, rshift, ralt, rgui, - // zig fmt: on - _, + pub const boot_keyboard = blk: { + var ret: Report = .generic_desktop; + ret.add_raw(.local_usage_enum(.{ .generic_desktop = .keyboard })); + ret.add_raw(.{ .main_collection = .Application }); + // Input: modifier key bitmap + ret.add_data_dynamic("modifiers", u8, .keyboard, .lctrl, 8, .in); + // Reserved 8 bits + ret.add_data_static(8, .in); + // Output: indicator LEDs + ret.add_data_dynamic("led", u8, .led, .num_lock, 5, .out); + // Input: up to 6 pressed key codes + ret.add_data_selector("keys", .keyboard, 6, .in); + break :blk ret.finalize(); + }; }; -pub const boot_keyboard = [_]Item{ - .{ .global_usage_page = .generic_desktop }, - .local_usage_enum(.{ .generic_desktop = .keyboard }), - .{ .main_collection = .Application }, - // Input: modifier key bitmap - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0xE0, 0xE7 }, - .count = 8, - .Child = bool, - .dir = .in, - .type = .dynamic, - } }, - // Reserved 8 bits - .{ .data_static = .{ .in, u8 } }, - // Output: indicator LEDs - .{ .data = .{ - .usage = .{ .global_page = .led }, - .usage_range = .{ 1, 5 }, - .count = 5, - .Child = bool, - .dir = .out, - .type = .dynamic, - } }, - // Padding - .{ .data_static = .{ .out, u3 } }, - // Input: up to 6 pressed key codes - .{ .data = .{ - .usage = .{ .global_page = .keyboard }, - .usage_range = .{ 0x00, 0xff }, - .count = 6, - .Child = u8, - .dir = .in, - .type = .selector, - } }, - // End - .main_collection_end, -}; +const Report = @This(); + +reserved: u16 = 0, +items: []const Item, +names: [2][]const [:0]const u8, +types: [2][]const type, +attrs: [2][]const SFAttributes, + +pub fn finalize(self: Report) Finalized { + var ret = Finalized{ + .descriptor = Item.create_report(self.items ++ [_]Item{.main_collection_end}), + .in = undefined, + .out = undefined, + }; + for (&.{ usb.types.Dir.in, usb.types.Dir.out }) |dir| + @field(ret, @tagName(dir)) = @Struct( + .@"extern", + null, + self.names[@backingInt(dir)], + self.types[@backingInt(dir)], + self.attrs[@backingInt(dir)], + ); + return ret; +} + +pub fn add_raw(self: *Report, item: Item) void { + self.items = self.items ++ [_]Item{item}; +} + +pub fn add_data_static( + self: *Report, + num_bits: u16, + dir: usb.types.Dir, +) void { + self.add_data_static_no_field(num_bits, dir); + self.add_field(dir, "", @Int(.unsigned, num_bits)); +} + +pub fn add_data_dynamic( + self: *Report, + name: [:0]const u8, + BackingInt: type, + usage_page: Item.UsagePage, + first: usage_page.Type(), + count: u16, + dir: usb.types.Dir, +) void { + const T = usage_page.Type(); + self.add_data_non_static_no_field( + usage_page, + @backingInt(first), + @backingInt(first) + (count - 1), + count, + 1, + dir, + .dynamic, + ); + var names: [count + @intFromBool(count < @bitSizeOf(BackingInt))][:0]const u8 = undefined; + var types: [names.len]type = @splat(bool); + var attrs: [names.len]SFAttributes = @splat(.{}); + for (0..count) |i| + names[i] = @tagName(@as(T, @fromBackingInt(@backingInt(first) + i))); + + if (count < @bitSizeOf(BackingInt)) { + const Padding = @Int(.unsigned, @bitSizeOf(BackingInt) - count); + self.add_data_static_no_field(@bitSizeOf(Padding), dir); + names[count] = self.get_reserved_name(); + types[count] = Padding; + attrs[count].default_value_ptr = &@as(Padding, 0); + } + self.add_field(dir, name, @Struct(.@"packed", BackingInt, &names, &types, &attrs)); +} + +pub fn add_data_selector( + self: *Report, + name: [:0]const u8, + usage_page: Item.UsagePage, + count: u16, + dir: usb.types.Dir, +) void { + const T = usage_page.Type(); + self.add_data_non_static_no_field( + usage_page, + 0, + (1 << @bitSizeOf(T)) - 1, + count, + @bitSizeOf(T), + dir, + .selector, + ); + self.add_field(dir, name, [count]T); +} + +pub fn with_first_item(item: Item) Report { + return .{ + .reserved = 0, + .items = &.{item}, + .names = @splat(&.{}), + .types = @splat(&.{}), + .attrs = @splat(&.{}), + }; +} + +pub const generic_desktop = with_first_item(.{ .global_usage_page = .generic_desktop }); + +fn add_field(self: *Report, dir: usb.types.Dir, name: [:0]const u8, Type: type) void { + var attr = SFAttributes{ .@"align" = 1 }; + if (name.len > 0) + self.names[@backingInt(dir)] = self.names[@backingInt(dir)] ++ [_][:0]const u8{name} + else { + self.names[@backingInt(dir)] = self.names[@backingInt(dir)] ++ [_][:0]const u8{self.get_reserved_name()}; + attr.default_value_ptr = &@as(Type, 0); + } + self.types[@backingInt(dir)] = self.types[@backingInt(dir)] ++ [_]type{Type}; + self.attrs[@backingInt(dir)] = self.attrs[@backingInt(dir)] ++ [_]SFAttributes{attr}; +} + +fn get_reserved_name(self: *Report) [:0]const u8 { + defer self.reserved += 1; + return std.fmt.comptimePrint("reserved{}", .{self.reserved}); +} + +fn add_data_static_no_field( + self: *Report, + bitsize: u16, + dir: usb.types.Dir, +) void { + self.items = self.items ++ [_]Item{ + .{ .global_report_count = 1 }, + .{ .global_report_size = bitsize }, + .main_io(dir, .static), + }; +} + +fn add_data_non_static_no_field( + self: *Report, + usage_page: Item.UsagePage, + range_min: i32, + range_max: i32, + count: u16, + bitsize: u16, + dir: usb.types.Dir, + data_type: Item.InputOutput, +) void { + self.items = self.items ++ [_]Item{ + .{ .global_usage_page = usage_page }, + .{ .local_usage_min = range_min }, + .{ .local_usage_max = range_max }, + .{ .global_logical_min = 0 }, + .{ .global_logical_max = (1 << bitsize) - 1 }, + .{ .global_report_count = count }, + .{ .global_report_size = bitsize }, + .main_io(dir, data_type), + }; +} diff --git a/core/src/core/usb/drivers/HID.zig b/core/src/core/usb/drivers/HID.zig index 341a81dfd..b5caecd74 100644 --- a/core/src/core/usb/drivers/HID.zig +++ b/core/src/core/usb/drivers/HID.zig @@ -15,8 +15,11 @@ pub const Descriptor = extern struct { }; /// HID Driver with an IN and OUT endpoint -pub fn Runtime(InReport: type, OutReport: type, report_descriptor: []const u8) type { +pub fn Runtime(report: usb.HID_report.Finalized) type { return struct { + pub const ReportIn = report.in; + pub const ReportOut = report.out; + pub const RequestType = enum(u8) { GetReport = 0x01, GetIdle = 0x02, @@ -66,7 +69,7 @@ pub fn Runtime(InReport: type, OutReport: type, report_descriptor: []const u8) t if (request_code == .get_descriptor and hid_desc_type == .HID) return std.mem.asBytes(&self.descriptor.hid) else if (request_code == .get_descriptor and hid_desc_type == .Report) - return report_descriptor; + return report.descriptor; }, .class => { const hid_request_type: RequestType = @fromBackingInt(setup.request); @@ -120,34 +123,34 @@ pub fn Runtime(InReport: type, OutReport: type, report_descriptor: []const u8) t self.rx_ready.store(true, .seq_cst); } - pub fn send_report(self: *@This(), report: *const InReport) bool { + pub fn send_report(self: *@This(), rep: *const ReportIn) bool { if (!self.tx_ready.load(.seq_cst)) return false; self.tx_ready.store(false, .seq_cst); const len = self.device.ep_writev( self.descriptor.ep_in.endpoint.num, - &.{std.mem.asBytes(report)}, + &.{std.mem.asBytes(rep)}, ); - log.debug("sent report {} {any}", .{ len, report }); + log.debug("sent report {} {any}", .{ len, rep }); return true; } - pub fn receive_report(self: *@This()) ?OutReport { + pub fn receive_report(self: *@This()) ?ReportOut { if (!self.rx_ready.load(.seq_cst)) return null; self.rx_ready.store(false, .seq_cst); - var report: OutReport = undefined; + var rep: ReportOut = undefined; const ep_num = self.descriptor.ep_out.endpoint.num; - const len = self.device.ep_readv(ep_num, &.{std.mem.asBytes(&report)}); + const len = self.device.ep_readv(ep_num, &.{std.mem.asBytes(&rep)}); self.device.ep_listen(ep_num, @intCast(self.descriptor.ep_out.max_packet_size.native())); - log.debug("received report {} {any}", .{ len, report }); + log.debug("received report {} {any}", .{ len, rep }); - return report; + return rep; } }; } @@ -160,24 +163,17 @@ protocol: ClassCode.Protocol(), itf_string: []const u8 = "", poll_interval: u8, country_code: usb.descriptor.HID.CountryCode = .NotSupported, -report_descriptor: []const usb.HID_report.Item, -InReport: type, -OutReport: type, +report: usb.HID_report.Finalized, pub fn driver_info( comptime self: Driver, comptime device_capabilities: usb.DeviceCapabilities, alloc: *usb.DescriptorAllocator, ) usb.DriverInfo(Descriptor) { - assert(@sizeOf(self.InReport) <= device_capabilities.max_packet_size); - assert(@sizeOf(self.OutReport) <= device_capabilities.max_packet_size); - const report_descriptor = usb.HID_report.Item.create_report(self.report_descriptor); + assert(@sizeOf(self.report.in) <= device_capabilities.max_packet_size); + assert(@sizeOf(self.report.out) <= device_capabilities.max_packet_size); return .{ - .Runtime = Runtime( - self.InReport, - self.OutReport, - report_descriptor, - ), + .Runtime = Runtime(self.report), .descriptor = .{ .interface = .{ .interface_number = alloc.next_itf(), @@ -189,16 +185,16 @@ pub fn driver_info( .hid = .{ .country_code = self.country_code, .num_descriptors = 1, - .report_length = .from(report_descriptor.len), + .report_length = .from(self.report.descriptor.len), }, .ep_out = .interrupt( alloc.next_ep(.out), - @sizeOf(self.OutReport), + @sizeOf(self.report.out), self.poll_interval, ), .ep_in = .interrupt( alloc.next_ep(.in), - @sizeOf(self.InReport), + @sizeOf(self.report.in), self.poll_interval, ), }, diff --git a/examples/nordic/nrf5x/src/usb_hid.zig b/examples/nordic/nrf5x/src/usb_hid.zig index 03944dc99..eb80ddd9f 100644 --- a/examples/nordic/nrf5x/src/usb_hid.zig +++ b/examples/nordic/nrf5x/src/usb_hid.zig @@ -10,7 +10,6 @@ const time = nrf.time; const USBD = nrf.usbd.USBD; const clocks = nrf.clocks; const uart = nrf.uart.num(0); -const Keycode = usb.HID_report.BootKeycode; pub const panic = microzig.panic; @@ -28,33 +27,12 @@ comptime { _ = microzig.export_startup(); } -pub const KeyboardInReport = extern struct { - modifiers: usb.HID_report.BootKeyboardModifiers, - reserved: u8 = 0, - keys: [6]Keycode, - - comptime { - std.debug.assert(@sizeOf(@This()) == 8); - } - - pub const empty: @This() = .{ .modifiers = .none, .keys = @splat(.reserved) }; -}; - -pub const KeyboardOutReport = packed struct(u8) { - num_lock: bool, - caps_lock: bool, - scroll_lock: bool, - padding: u5 = 0, -}; - const hid_driver_options: usb.drivers.HID_Interrupt = .{ .subclass = .Boot, .protocol = .Boot, .itf_string = "Boot Keyboard", .poll_interval = 1, .report_descriptor = &usb.HID_report.boot_keyboard, - .InReport = KeyboardInReport, - .OutReport = KeyboardOutReport, }; var usb_device: USBD = undefined; @@ -84,7 +62,7 @@ pub fn main() !void { var old: u64 = time.get_time_since_boot().to_us(); var new: u64 = 0; - const message: []const Keycode = &.{ .h, .e, .l, .l, .o, .space, .w, .o, .r, .l, .d, .caps_lock, .enter }; + const message: []const usb.HID_report.Keycode = &.{ .h, .e, .l, .l, .o, .space, .w, .o, .r, .l, .d, .caps_lock, .enter }; var idx: usize = 0; while (true) { @@ -98,16 +76,14 @@ pub fn main() !void { idx = 0; } else { std.log.info("report {}", .{idx}); - idx += @intFromBool(if (idx & 1 == 0 and idx < 2 * message.len) - drivers.keyboard.send_report( - &.{ .modifiers = .none, .keys = .{message[@intCast(idx / 2)]} ++ @as([5]Keycode, @splat(.reserved)) }, - ) - else - drivers.keyboard.send_report(&.empty)); + var report = std.mem.zeroes(@TypeOf(drivers.keyboard).ReportIn); + if (idx & 1 == 0 and idx < 2 * message.len) + report.keys[0] = message[@intCast(idx / 2)]; + idx += @intFromBool(drivers.keyboard.send_report(&report)); } if (drivers.keyboard.receive_report()) |report| - board.led1.put(@intFromBool(report.caps_lock)); + board.led1.put(@intFromBool(report.led.caps_lock)); } } } diff --git a/examples/raspberrypi/rp2xxx/src/usb_hid.zig b/examples/raspberrypi/rp2xxx/src/usb_hid.zig index c2b4c4767..660080b62 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_hid.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_hid.zig @@ -5,7 +5,6 @@ const rp2xxx = microzig.hal; const time = rp2xxx.time; const usb = microzig.core.usb; const USB_Device = rp2xxx.usb.Polled(.{}); -const Keycode = usb.HID_report.BootKeycode; pub const std_options = microzig.std_options(.{ .log_level = .debug, @@ -21,33 +20,12 @@ comptime { _ = microzig.export_startup(); } -pub const KeyboardInReport = extern struct { - modifiers: usb.HID_report.BootKeyboardModifiers, - reserved: u8 = 0, - keys: [6]Keycode, - - comptime { - std.debug.assert(@sizeOf(@This()) == 8); - } - - pub const empty: @This() = .{ .modifiers = .none, .keys = @splat(.reserved) }; -}; - -pub const KeyboardOutReport = packed struct(u8) { - num_lock: bool, - caps_lock: bool, - scroll_lock: bool, - padding: u5 = 0, -}; - const hid_driver_options: usb.drivers.HID_Interrupt = .{ .subclass = .Boot, .protocol = .Boot, .itf_string = "Boot Keyboard", .poll_interval = 1, - .report_descriptor = &usb.HID_report.boot_keyboard, - .InReport = KeyboardInReport, - .OutReport = KeyboardOutReport, + .report = .boot_keyboard, }; var usb_device: USB_Device = undefined; @@ -92,7 +70,7 @@ pub fn main() !void { var old: u64 = time.get_time_since_boot().to_us(); var new: u64 = 0; - const message: []const Keycode = &.{ .h, .e, .l, .l, .o, .space, .w, .o, .r, .l, .d, .caps_lock, .enter }; + const message: []const usb.HID_report.Keycode = &.{ .h, .e, .l, .l, .o, .space, .w, .o, .r, .l, .d, .caps_lock, .enter }; var idx: usize = 0; while (true) { @@ -105,16 +83,14 @@ pub fn main() !void { old = new; idx = 0; } else { - idx += @intFromBool(if (idx & 1 == 0 and idx < 2 * message.len) - drivers.keyboard.send_report( - &.{ .modifiers = .none, .keys = .{message[@intCast(idx / 2)]} ++ @as([5]Keycode, @splat(.reserved)) }, - ) - else - drivers.keyboard.send_report(&.empty)); + var report = std.mem.zeroes(@TypeOf(drivers.keyboard).ReportIn); + if (idx & 1 == 0 and idx < 2 * message.len) + report.keys[0] = message[@intCast(idx / 2)]; + idx += @intFromBool(drivers.keyboard.send_report(&report)); } if (drivers.keyboard.receive_report()) |report| - pins.led.put(@intFromBool(report.caps_lock)); + pins.led.put(@intFromBool(report.led.caps_lock)); } } } From f7038a3402bb461d97a2b5978ddae4a3e30c77e8 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Thu, 12 Nov 2026 00:56:19 +0100 Subject: [PATCH 23/28] Add more keycodes --- core/src/core/usb/HID_report.zig | 56 ++++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 2 deletions(-) diff --git a/core/src/core/usb/HID_report.zig b/core/src/core/usb/HID_report.zig index 5a018340c..2fb34817f 100644 --- a/core/src/core/usb/HID_report.zig +++ b/core/src/core/usb/HID_report.zig @@ -4,7 +4,10 @@ const assert = std.debug.assert; const SFAttributes = std.builtin.Type.Struct.FieldAttributes; pub const Keycode = enum(u8) { - // Codes taken from https://gist.github.com/mildsunrise/4e231346e2078f440969cdefb6d4caa3 + // Codes taken from: + // https://gist.github.com/mildsunrise/4e231346e2078f440969cdefb6d4caa3 + // https://gist.github.com/MightyPork/6da26e382a7ad91b5496ee55fdc73db2 + // zig fmt: off reserved = 0x00, error_roll_over, post_fail, error_undefined, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, @@ -13,15 +16,64 @@ pub const Keycode = enum(u8) { @"-", @"=", @"[", @"]", @"\\", @"non_us_#", @";", @"'", @"`", @",", @".", @"/", caps_lock, f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, + print_screen, scroll_lock, pause, insert, home, page_up, delete_forward, end, page_down, right_arrow, left_arrow, down_arrow, up_arrow, num_lock, + kpad_div, kpad_mul, kpad_sub, kpad_add, kpad_enter, kpad_1, kpad_2, kpad_3, kpad_4, kpad_5, kpad_6, kpad_7, kpad_8, kpad_9, kpad_0, kpad_delete, @"non_us_\\", application, power, @"kpad_=", + f13, f14, f15, f16, f17, f18, f19, f20, f21, f22, f23, f24, - lctrl = 224, lshift, lalt, lgui, rctrl, rshift, ralt, rgui, + + execute, help, menu, select, stop, again, undo, cut, copy, paste, find, + mute, volumeup, volumedown, + locking_caps_lock, locking_num_lock, locking_scroll_lock, + + @"kpad_,", @"kpad_alternate_=", + + international1, international2, international3, international4, international5, + international6, international7, international8, international9, + lang1, lang2, lang3, lang4, lang5, lang6, lang7, lang8, lang9, + + alternate_erase, sysreq_attention, cancel, clear, prior, @"return", + separator, out, oper, clear_again, crsel_props, exsel, + + kpad_00 = 0xb0, kpad_000, kpad_thousands_separator, kpad_decimal_separator, + kpad_currency_unit, kpad_currency_subunit, + @"kpad_(", @"kpad_)", @"kpad_{", @"kpad_}", kpad_tab, kpad_backspace, + kpad_a, kpad_b, kpad_c, kpad_d, kpad_e, kpad_f, + kpad_xor, @"kpad_^", @"kpad_%", @"kpad_<", @"kpad_>", @"kpad_&", @"kpad_&&", + @"kpad_|", @"kpad_||", @"kpad_:", @"kpad_#", kpad_space, @"kpad_@", @"kpad_!", + kpad_memory_store, kpad_memory_recall, kpad_memory_clear, kpad_memory_add, + kpad_memory_subtract, kpad_memory_multiply, kpad_memory_divide, @"kpad_+/-", + kpad_clear, kpad_clear_entry, kpad_binary, kpad_octal, kpad_decimal, kpad_hexadecimal, + + lctrl = 0xe0, lshift, lalt, lgui, rctrl, rshift, ralt, rgui, + + media_playpause, media_stopcd, media_previoussong, media_nextsong, + media_ejectcd, media_volumeup, media_volumedown, media_mute, + media_www, media_back, media_forward, media_stop, media_find, + media_scrollup, media_scrolldown, media_edit, media_sleep, + media_coffee, media_refresh, media_calc, // zig fmt: on _, + + // Aliases + const open: @This() = .execute; + const props: @This() = .menu; + const front: @This() = .select; + const ro: @This() = .international1; + const katakanahiragana: @This() = .international2; + const yen: @This() = .international3; + const henkan: @This() = .international4; + const muhenkan: @This() = .international5; + const kpjpcomma: @This() = .international6; + const hangeul: @This() = .lang1; + const hanja: @This() = .lang2; + const katakana: @This() = .lang3; + const hiragana: @This() = .lang4; + const zenkakuhankaku: @This() = .lang5; }; pub const Ledcode = enum(u3) { From 80783e64d212f332c45c6cf7d564bae5979e82c5 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Thu, 12 Nov 2026 01:13:54 +0100 Subject: [PATCH 24/28] Add some interface checks --- core/src/core/usb.zig | 9 ++++++--- core/src/core/usb/HID_report.zig | 1 - core/src/core/usb/configuration.zig | 28 +++++++++++++++++----------- 3 files changed, 23 insertions(+), 15 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index b520d5b03..6b7b662bf 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -397,9 +397,12 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { const itf_num: u8 = @truncate(setup.index.native()); const num_interfaces = configurations[0].interface2driver.len; switch (itf_num) { - inline else => |itf| if (comptime itf < num_interfaces) - return @field(self.driver_data.?, configurations[0].interface2driver[itf]).class_request(setup) - else { + inline else => |itf| if (comptime itf < num_interfaces) { + const driver = &@field(self.driver_data.?, configurations[0].interface2driver[itf]); + if (!@hasDecl(@TypeOf(driver.*), "class_request")) + @compileError(@typeName(@TypeOf(driver.*)) ++ ".class_request() missing"); + return driver.class_request(setup); + } else { log.warn("Interface index ({}) out of range ({})", .{ itf_num, num_interfaces }); return nak; }, diff --git a/core/src/core/usb/HID_report.zig b/core/src/core/usb/HID_report.zig index 2fb34817f..23eb295fd 100644 --- a/core/src/core/usb/HID_report.zig +++ b/core/src/core/usb/HID_report.zig @@ -1,6 +1,5 @@ const std = @import("std"); const usb = @import("../usb.zig"); -const assert = std.debug.assert; const SFAttributes = std.builtin.Type.Struct.FieldAttributes; pub const Keycode = enum(u8) { diff --git a/core/src/core/usb/configuration.zig b/core/src/core/usb/configuration.zig index 86d1be936..d6b65b2c3 100644 --- a/core/src/core/usb/configuration.zig +++ b/core/src/core/usb/configuration.zig @@ -3,6 +3,7 @@ const usb = @import("../usb.zig"); const assert = std.debug.assert; const descriptor = usb.descriptor; +const SFAttributes = std.builtin.Type.Struct.FieldAttributes; pub const Options = struct { attributes: descriptor.Configuration.Attributes, @@ -44,7 +45,7 @@ pub fn Create( // Descriptor var desc_field_types: [driver_names.len]type = undefined; - var desc_field_attrs: [driver_names.len]std.builtin.Type.Struct.FieldAttributes = undefined; + var desc_field_attrs: [driver_names.len]SFAttributes = undefined; // EndpointHandlers var ep_handler_types: [2][16]type = @splat(@splat(void)); @@ -52,7 +53,7 @@ pub fn Create( // DriverAlloc var driver_alloc_types: [driver_names.len]type = undefined; - var driver_alloc_attrs: [driver_names.len]std.builtin.Type.Struct.FieldAttributes = undefined; + var driver_alloc_attrs: [driver_names.len]SFAttributes = undefined; for ( driver_names, @@ -70,8 +71,11 @@ pub fn Create( *driver_alloc_attr, | { // Get type information for the current driver - const drv = @field(driver_config, driver_field_name); - const driver_data = drv.driver_info(device_capabilities, &alloc); + const driver = @field(driver_config, driver_field_name); + const Driver = @TypeOf(driver); + if (!@hasDecl(Driver, "driver_info")) + @compileError(@typeName(Driver) ++ ".driver_info() missing"); + const driver_data = driver.driver_info(device_capabilities, &alloc); Descriptor.* = @TypeOf(driver_data.descriptor); assert(@alignOf(Descriptor.*) == 1); Runtime.* = driver_data.Runtime; @@ -93,10 +97,8 @@ pub fn Create( descriptor.InterfaceAssociation => .{ desc.first_interface, desc.interface_count }, descriptor.Interface => .{ desc.interface_number, 1 }, else => |T| @compileError( - "Expected first descriptor of driver " ++ - @typeName(@TypeOf(drv)) ++ - " to be of type Interface or InterfaceAssociation descriptor, got: " ++ - @typeName(T), + "Expected first descriptor of driver " ++ @typeName(Driver) ++ + " to be of type Interface or InterfaceAssociation descriptor, got: " ++ @typeName(T), ), }; if (itf_start != interface2driver.len) @@ -213,14 +215,18 @@ pub fn Create( device_itf.ep_open(desc); } - const drv = @field(driver_config, driver_field_name); + const driver = @field(driver_config, driver_field_name); const runtime = &@field(driver_data, driver_field_name); const alloc = &@field(driver_alloc, driver_field_name); + + if (!@hasDecl(@TypeOf(runtime.*), "init")) + @compileError(@typeName(@TypeOf(runtime.*)) ++ ".init() missing"); + // Don't pass *void around if (@TypeOf(alloc) != *void) - runtime.init(drv, &cfg, device_itf, alloc) + runtime.init(driver, &cfg, device_itf, alloc) else - runtime.init(drv, &cfg, device_itf); + runtime.init(driver, &cfg, device_itf); // Open IN endpoint last so that callbacks can happen inline for (desc_info.field_names, desc_info.field_types) |field_name, field_type| { From 721975ff161ddb1da032006111afc2b9affdeb21 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Thu, 12 Nov 2026 01:14:53 +0100 Subject: [PATCH 25/28] Fix typo --- core/src/core/usb.zig | 4 ++-- core/src/core/usb/drivers/HID.zig | 2 +- examples/nordic/nrf5x/src/usb_hid.zig | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index 6b7b662bf..d4fc23c2e 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -60,9 +60,9 @@ pub const DescriptorAllocator = struct { /// Device-specific information pub const DeviceCapabilities = struct { max_supported_bcd_usb: types.Version = .v1_00, - /// Maximimum packet size on ep0 + /// Maximum packet size on ep0 max_packet_size0: types.PacketLength, - /// Maximimum packet size on other endpoints + /// Maximum packet size on other endpoints max_packet_size: types.PacketLength, default_vendor: ?Options.IdStringPair = null, default_product: ?Options.IdStringPair = null, diff --git a/core/src/core/usb/drivers/HID.zig b/core/src/core/usb/drivers/HID.zig index b5caecd74..fad1d08eb 100644 --- a/core/src/core/usb/drivers/HID.zig +++ b/core/src/core/usb/drivers/HID.zig @@ -91,7 +91,7 @@ pub fn Runtime(report: usb.HID_report.Finalized) type { // or vice versa. // // For now, this request is ACKed without doing anything; in practice, - // the OS will reuqest the report protocol anyway, so usually only one format is needed. + // the OS will request the report protocol anyway, so usually only one format is needed. // Unless the report format matches the boot protocol exactly (see ReportDescriptorKeyboard), // our device might not work in a limited BIOS environment. // diff --git a/examples/nordic/nrf5x/src/usb_hid.zig b/examples/nordic/nrf5x/src/usb_hid.zig index eb80ddd9f..6bb1c32bf 100644 --- a/examples/nordic/nrf5x/src/usb_hid.zig +++ b/examples/nordic/nrf5x/src/usb_hid.zig @@ -32,7 +32,7 @@ const hid_driver_options: usb.drivers.HID_Interrupt = .{ .protocol = .Boot, .itf_string = "Boot Keyboard", .poll_interval = 1, - .report_descriptor = &usb.HID_report.boot_keyboard, + .report = &usb.HID_report.boot_keyboard, }; var usb_device: USBD = undefined; From 652f3e3e875674f5f4afcac80c46414a29df9c95 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Thu, 12 Nov 2026 01:38:46 +0100 Subject: [PATCH 26/28] One last fix --- examples/nordic/nrf5x/src/usb_hid.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/nordic/nrf5x/src/usb_hid.zig b/examples/nordic/nrf5x/src/usb_hid.zig index 6bb1c32bf..26eb0e021 100644 --- a/examples/nordic/nrf5x/src/usb_hid.zig +++ b/examples/nordic/nrf5x/src/usb_hid.zig @@ -32,7 +32,7 @@ const hid_driver_options: usb.drivers.HID_Interrupt = .{ .protocol = .Boot, .itf_string = "Boot Keyboard", .poll_interval = 1, - .report = &usb.HID_report.boot_keyboard, + .report = .boot_keyboard, }; var usb_device: USBD = undefined; From 779d1efaa068f1c88bbe7ae4fbc17251f75ab813 Mon Sep 17 00:00:00 2001 From: Piotr Fila Date: Sun, 15 Nov 2026 18:09:38 +0100 Subject: [PATCH 27/28] Minor fixes --- core/src/core/usb.zig | 4 +++- core/src/core/usb/configuration.zig | 15 ++++++++++++--- core/src/core/usb/drivers/EchoExample.zig | 2 +- examples/nordic/nrf5x/src/usb_cdc.zig | 2 +- examples/nordic/nrf5x/src/usb_hid.zig | 2 +- examples/raspberrypi/rp2xxx/src/usb_cdc.zig | 2 +- examples/raspberrypi/rp2xxx/src/usb_hid.zig | 2 +- examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig | 2 +- examples/wch/ch32v/src/usb_cdc.zig | 2 +- 9 files changed, 22 insertions(+), 11 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index d4fc23c2e..3c4c34704 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -1,8 +1,10 @@ const std = @import("std"); +const configuration = @import("usb/configuration.zig"); const assert = std.debug.assert; const log = std.log.scoped(.usb_ctrl); -pub const configuration = @import("usb/configuration.zig"); +pub const Configuration = configuration.Configuration; +pub const ConfigurationOptions = configuration.Options; pub const descriptor = @import("usb/descriptor.zig"); pub const drivers = struct { pub const CDC = @import("usb/drivers/CDC.zig"); diff --git a/core/src/core/usb/configuration.zig b/core/src/core/usb/configuration.zig index d6b65b2c3..e00067256 100644 --- a/core/src/core/usb/configuration.zig +++ b/core/src/core/usb/configuration.zig @@ -15,7 +15,7 @@ pub const Options = struct { unique_endpoints: bool = true, }; -pub fn Create( +pub fn Configuration( options: Options, driver_config: anytype, ) type { @@ -32,7 +32,10 @@ pub fn Create( EndpointHandlers: type, interface2driver: []const DriverName, - pub fn create(device_capabilities: usb.DeviceCapabilities, strings: []const []const u8) struct { @This(), []const []const u8 } { + pub fn create( + device_capabilities: usb.DeviceCapabilities, + strings: []const []const u8, + ) struct { @This(), []const []const u8 } { var alloc = usb.DescriptorAllocator.init(options.unique_endpoints, strings); const configuration_s = alloc.string(options.name); const driver_names = @typeInfo(@TypeOf(driver_config)).@"struct".field_names; @@ -203,7 +206,13 @@ pub fn Create( }; } - pub fn init(comptime self: @This(), device_itf: *usb.DeviceInterface, driver_data: *self.RuntimeData, driver_alloc: anytype, comptime config_descriptor: anytype) void { + pub fn init( + comptime self: @This(), + device_itf: *usb.DeviceInterface, + driver_data: *self.RuntimeData, + driver_alloc: anytype, + comptime config_descriptor: anytype, + ) void { inline for (@typeInfo(self.RuntimeData).@"struct".field_names) |driver_field_name| { const cfg = @field(config_descriptor.drv, driver_field_name); const desc_info = @typeInfo(@TypeOf(cfg)).@"struct"; diff --git a/core/src/core/usb/drivers/EchoExample.zig b/core/src/core/usb/drivers/EchoExample.zig index c6c597433..0e2d8914d 100644 --- a/core/src/core/usb/drivers/EchoExample.zig +++ b/core/src/core/usb/drivers/EchoExample.zig @@ -105,7 +105,7 @@ pub const Runtime = struct { }; /// `Runtime` type can be generic, in which case the driver type -/// is the only paramater passed. It may be a good idea to make this function +/// is the only parameter passed. It may be a good idea to make this function /// a wrapper around another, that only takes a subset of the parameters. /// This way the generic types are much more readable in zig error output /// and potentially less code is duplicated when using multiple driver instances diff --git a/examples/nordic/nrf5x/src/usb_cdc.zig b/examples/nordic/nrf5x/src/usb_cdc.zig index 9e417e28e..1f90d951d 100644 --- a/examples/nordic/nrf5x/src/usb_cdc.zig +++ b/examples/nordic/nrf5x/src/usb_cdc.zig @@ -35,7 +35,7 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .device_capabilities = USBD.device_capabilities, -}, &.{usb.configuration.Create( +}, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ .serial = usb.drivers.CDC{ .itf_notifi_str = "Board CDC", .itf_data_str = "Board CDC Data" } }, )}) = .init; diff --git a/examples/nordic/nrf5x/src/usb_hid.zig b/examples/nordic/nrf5x/src/usb_hid.zig index 26eb0e021..0ab0ebf7c 100644 --- a/examples/nordic/nrf5x/src/usb_hid.zig +++ b/examples/nordic/nrf5x/src/usb_hid.zig @@ -42,7 +42,7 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .device_capabilities = USBD.device_capabilities, -}, &.{usb.configuration.Create( +}, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ .keyboard = hid_driver_options }, )}) = .init; diff --git a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig index e340675a4..a099b9cc2 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_cdc.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_cdc.zig @@ -18,7 +18,7 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .device_capabilities = USB_Device.device_capabilities, -}, &.{usb.configuration.Create( +}, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ .serial = usb.drivers.CDC{ .itf_notifi_str = "Board CDC", .itf_data_str = "Board CDC Data" }, diff --git a/examples/raspberrypi/rp2xxx/src/usb_hid.zig b/examples/raspberrypi/rp2xxx/src/usb_hid.zig index 660080b62..4c07c3cca 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_hid.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_hid.zig @@ -35,7 +35,7 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .device_capabilities = USB_Device.device_capabilities, -}, &.{usb.configuration.Create( +}, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ .keyboard = hid_driver_options, diff --git a/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig b/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig index ae59afd41..baa00ed2b 100644 --- a/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig +++ b/examples/raspberrypi/rp2xxx/src/usb_raw_echo.zig @@ -17,7 +17,7 @@ var usb_controller: usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .device_capabilities = USB_Device.device_capabilities, -}, &.{usb.configuration.Create( +}, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ .echo = usb.drivers.EchoExample{}, diff --git a/examples/wch/ch32v/src/usb_cdc.zig b/examples/wch/ch32v/src/usb_cdc.zig index 047e7c8bc..5e27663cf 100644 --- a/examples/wch/ch32v/src/usb_cdc.zig +++ b/examples/wch/ch32v/src/usb_cdc.zig @@ -33,7 +33,7 @@ const USB_Controller = usb.DeviceController(.{ .bcd_device = .v1_00, .serial = "someserial", .device_capabilities = USB_Device.device_capabilities, -}, &.{usb.configuration.Create( +}, &.{usb.Configuration( .{ .attributes = .{ .self_powered = false }, .max_current_ma = 50 }, .{ .serial = usb.drivers.CDC{ .itf_notifi_str = "Board CDC", .itf_data_str = "Board CDC Data" } }, )}); From a536074687723735f06cd0d54c3c98514d68d55a Mon Sep 17 00:00:00 2001 From: Vesim Date: Mon, 16 Nov 2026 12:32:08 +0100 Subject: [PATCH 28/28] feat(usb): Add suspend and resume support --- core/src/core/usb.zig | 119 +++++++++++++++++++++++- port/raspberrypi/rp2xxx/src/hal/usb.zig | 41 ++++++++ 2 files changed, 156 insertions(+), 4 deletions(-) diff --git a/core/src/core/usb.zig b/core/src/core/usb.zig index 3c4c34704..9adbe5178 100644 --- a/core/src/core/usb.zig +++ b/core/src/core/usb.zig @@ -68,6 +68,8 @@ pub const DeviceCapabilities = struct { max_packet_size: types.PacketLength, default_vendor: ?Options.IdStringPair = null, default_product: ?Options.IdStringPair = null, + /// Ports that enable this must also provide the `signal_resume` vtable function. + supports_remote_wakeup: bool = false, }; /// Wraps a Descriptor type. Returned by the `create` method of the Descriptor. @@ -83,6 +85,13 @@ pub fn DriverInfo(Descriptor: type) type { }; } +pub const RemoteWakeupError = error{ + NotSupported, + NotEnabledByHost, + NotConfigured, + NotSuspended, +}; + /// USB Device interface /// Any device implementation used with DeviceController must implement these functions pub const DeviceInterface = struct { @@ -92,6 +101,7 @@ pub const DeviceInterface = struct { ep_listen: *const fn (*DeviceInterface, types.Endpoint.Num, types.PacketLength) void, ep_open: *const fn (*DeviceInterface, *const descriptor.Endpoint) void, set_address: *const fn (*DeviceInterface, u7) void, + signal_resume: ?*const fn (*DeviceInterface) RemoteWakeupError!void = null, }; vtable: *const VTable, @@ -131,6 +141,12 @@ pub const DeviceInterface = struct { pub fn set_address(self: *@This(), addr: u7) void { return self.vtable.set_address(self, addr); } + + /// Drive resume signaling on the bus to wake the host + pub fn signal_resume(self: *@This()) RemoteWakeupError!void { + const f = self.vtable.signal_resume orelse return error.NotSupported; + return f(self); + } }; pub fn EndpointHandler(Driver: type) type { @@ -171,6 +187,10 @@ pub const Options = struct { serial: []const u8, /// Largest packet length the hardware supports. Must be a power of 2 and at least 8. device_capabilities: DeviceCapabilities, + /// Only called when the bus actually enters suspend. + on_suspend: ?*const fn () void = null, + /// Only called when the bus actually leaves suspend. + on_resume: ?*const fn () void = null, }; pub fn validate_controller(T: type) void { @@ -272,6 +292,10 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { driver_data: ?configurations[0].RuntimeData, /// Additional driver allocations (size is comptime-known) driver_alloc: configurations[0].DriverAlloc, + /// Whether the host has enabled the remote wakeup feature + remote_wakeup_enabled: bool, + /// Whether the bus is currently suspended. + is_suspended: bool, /// Initial values pub const init: @This() = .{ @@ -280,6 +304,8 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { .tx_slice = null, .driver_data = null, .driver_alloc = undefined, + .remote_wakeup_enabled = false, + .is_suspended = false, }; /// Returns a pointer to the drivers @@ -356,6 +382,56 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { self.* = .init; } + /// Called by the device implementation when the bus has been suspended. + pub fn on_suspend(self: *@This(), device_itf: *DeviceInterface) void { + _ = device_itf; + log.debug("on_suspend", .{}); + + if (!self.is_suspended) { + self.is_suspended = true; + if (options.on_suspend) |cb| cb(); + } + } + + /// Called by the device implementation when the bus has resumed, + /// either by the host or by the device itself via remote wakeupe. + pub fn on_resume(self: *@This(), device_itf: *DeviceInterface) void { + _ = device_itf; + log.debug("on_resume", .{}); + + if (self.is_suspended) { + self.is_suspended = false; + if (options.on_resume) |cb| cb(); + } + } + + /// Returns whether the bus is currently suspended. + pub fn suspended(self: *@This()) bool { + return self.is_suspended; + } + + /// Attempt to wake up the host with a device-initiated remote wakeup. + pub fn remote_wakeup(self: *@This(), device_itf: *DeviceInterface) RemoteWakeupError!void { + if (!self.remote_wakeup_enabled) { + log.debug("remote wakeup requested, but not enabled by host", .{}); + return error.NotEnabledByHost; + } + if (self.cfg_num == 0) { + log.debug("remote wakeup requested, but device is not configured", .{}); + return error.NotConfigured; + } + if (!self.is_suspended) { + log.debug("remote wakeup requested, but bus is not suspended", .{}); + return error.NotSuspended; + } + device_itf.signal_resume() catch |err| { + log.debug("remote wakeup requested, but device implementation refused: {s}", .{@errorName(err)}); + return err; + }; + // In the case of self-initiated resume we call the callback directly + self.on_resume(device_itf); + } + // Utility functions fn process_device_setup(self: *@This(), device_itf: *DeviceInterface, setup: *const types.SetupPacket) ?[]const u8 { @@ -366,21 +442,53 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { switch (request) { .get_status => { const attr = config_descriptor.first.attributes; - const status: types.DeviceStatus = comptime .create(attr.self_powered, false); - return std.mem.asBytes(&status); + const S = struct { + const responses = [2]types.DeviceStatus{ + .create(attr.self_powered, false), + .create(attr.self_powered, true), + }; + }; + return std.mem.asBytes(&S.responses[@intFromBool(self.remote_wakeup_enabled)]); }, .set_address => self.new_address = @truncate(setup.value.native()), .set_configuration => self.process_set_config(device_itf, setup.value.native()), .get_descriptor => return get_descriptor(setup.value.native()), .set_feature => { - const feature: types.FeatureSelector = @fromBackingInt(@intCast(setup.value.native() >> 8)); + const feature: types.FeatureSelector = @fromBackingInt(@truncate(setup.value.native())); switch (feature) { - .DeviceRemoteWakeup, .EndpointHalt => {}, + .DeviceRemoteWakeup => { + if (comptime !config_descriptor.first.attributes.can_remote_wakeup) { + log.warn("Host set DEVICE_REMOTE_WAKEUP, but we do not advertise it", .{}); + return nak; + } + log.debug("Host enabled remote wakeup", .{}); + self.remote_wakeup_enabled = true; + }, + .EndpointHalt => { + // TODO: Implement endpoint halting. + }, // TODO: https://github.com/ZigEmbeddedGroup/microzig/issues/453 .TestMode => return nak, else => return nak, } }, + .clear_feature => { + const feature: types.FeatureSelector = @fromBackingInt(@truncate(setup.value.native())); + switch (feature) { + .DeviceRemoteWakeup => { + if (comptime !config_descriptor.first.attributes.can_remote_wakeup) { + log.warn("Host cleared DEVICE_REMOTE_WAKEUP, but we do not advertise it", .{}); + return nak; + } + log.debug("Host disabled remote wakeup", .{}); + self.remote_wakeup_enabled = false; + }, + .EndpointHalt => { + // TODO: Implement endpoint halting. + }, + else => return nak, + } + }, else => { log.warn("Unsupported standard request: {}", .{setup.request}); return nak; @@ -440,6 +548,9 @@ pub fn DeviceController(options: Options, Configurations: []const type) type { if (self.driver_data) |*data_old| configurations[0].deinit(device_itf, data_old); + // (Re)configuration disables the remote wakeup feature. + self.remote_wakeup_enabled = false; + self.cfg_num = cfg_num; if (cfg_num == 0) self.driver_data = null diff --git a/port/raspberrypi/rp2xxx/src/hal/usb.zig b/port/raspberrypi/rp2xxx/src/hal/usb.zig index ddfb8acdc..609cb0cb4 100644 --- a/port/raspberrypi/rp2xxx/src/hal/usb.zig +++ b/port/raspberrypi/rp2xxx/src/hal/usb.zig @@ -93,6 +93,7 @@ pub fn Polled(config: Config) type { .RP2040 => .{ .id = 0x000A, .str = "Pico test device" }, .RP2350 => .{ .id = 0x000F, .str = "Pico 2 test device" }, }, + .supports_remote_wakeup = true, }; comptime { @@ -105,6 +106,7 @@ pub fn Polled(config: Config) type { .ep_listen = ep_listen, .ep_open = ep_open, .set_address = set_address, + .signal_resume = signal_resume, }; endpoints: [config.max_endpoints_count][2]HardwareEndpointData, @@ -180,6 +182,30 @@ pub fn Polled(config: Config) type { set_address(&self.interface, 0); controller.on_bus_reset(&self.interface); } + + // Has the suspend state changed? + if (ints.DEV_SUSPEND != 0) { + const suspended = peripherals.USB.SIE_STATUS.read().SUSPENDED != 0; + + peripherals.USB.SIE_STATUS.write(.{ .SUSPENDED = 1 }); + + if (suspended) { + log.debug("-- bus suspended --", .{}); + controller.on_suspend(&self.interface); + } else { + log.debug("-- bus resumed --", .{}); + controller.on_resume(&self.interface); + } + } + + // Has the host signaled a resume? + if (ints.DEV_RESUME_FROM_HOST != 0) { + log.debug("-- resume signaled by host --", .{}); + + peripherals.USB.SIE_STATUS.write(.{ .RESUME = 1 }); + + controller.on_resume(&self.interface); + } } pub fn init() @This() { @@ -242,6 +268,10 @@ pub fn Polled(config: Config) type { .BUS_RESET = 1, // We've gotten a setup request on EP0 .SETUP_REQ = 1, + // The suspend state has changed (entering or leaving suspend) + .DEV_SUSPEND = 1, + // The host has signaled a resume + .DEV_RESUME_FROM_HOST = 1, }); var self: @This() = .{ @@ -382,6 +412,17 @@ pub fn Polled(config: Config) type { peripherals.USB.ADDR_ENDP.write(.{ .ADDRESS = addr }); } + /// Device-initiated remote wakeup: signal a resume to the host by + /// driving the bus into K state. + fn signal_resume(_: *usb.DeviceInterface) usb.RemoteWakeupError!void { + comptime assert(device_capabilities.supports_remote_wakeup); + + if (peripherals.USB.SIE_STATUS.read().SUSPENDED == 0) + return error.NotSuspended; + + peripherals.USB.SIE_CTRL.modify(.{ .RESUME = 1 }); + } + /// On the RP2350 @memcpy uses unaligned accesses, /// which only work on SRAM and fault on peripheral memory. fn dpram_memcpy(dst: []u8, src: []const u8) void {