Repository navigation
feat(usb): Add suspend and resume support #1138
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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,11 @@ 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 { | ||
| return if (self.vtable.signal_resume) |f| f(self) else error.NotSupported; | ||
| } | ||
| }; | ||
|
|
||
| pub fn EndpointHandler(Driver: type) type { | ||
|
|
@@ -171,6 +186,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, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this should be handled by returning a value from poll rather than with callbacks |
||
| }; | ||
|
|
||
| pub fn validate_controller(T: type) void { | ||
|
|
@@ -272,6 +291,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 +303,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 +381,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) { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Log message if on_suspend was called while suspened would be nice |
||
| 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 +441,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)]); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Does a device really need to be self-powered for remote wakeup to work? |
||
| }, | ||
| .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: https://github.com/ZigEmbeddedGroup/microzig/issues/1144 | ||
| }, | ||
| // 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: https://github.com/ZigEmbeddedGroup/microzig/issues/1144 | ||
| }, | ||
| else => return nak, | ||
| } | ||
| }, | ||
| else => { | ||
| log.warn("Unsupported standard request: {}", .{setup.request}); | ||
| return nak; | ||
|
|
@@ -440,6 +547,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 | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| const std = @import("std"); | ||
| const microzig = @import("microzig"); | ||
|
|
||
| const rp2xxx = microzig.hal; | ||
| const time = rp2xxx.time; | ||
| const usb = microzig.core.usb; | ||
|
|
||
| const Deadline = microzig.drivers.time.Deadline; | ||
|
|
||
| // 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 handler sfor the picotool-controlled reset (ResetDriver). | ||
| var usb_controller: usb.DeviceController(.{ | ||
| .device_triple = .unspecified, | ||
| .bcd_device = .v1_00, | ||
| .serial = "someserial", | ||
| .device_capabilities = USB_Device.device_capabilities, | ||
| .on_suspend = on_suspend, | ||
| .on_resume = on_resume, | ||
| }, &.{usb.Configuration( | ||
| .{ | ||
| .attributes = .{ | ||
| .self_powered = false, | ||
| // this is required so the usb stack responds to DeviceRemoteWakeup set/clear feature | ||
| // from the host | ||
| .can_remote_wakeup = true, | ||
| }, | ||
| .max_current_ma = 50, | ||
| }, | ||
| .{ | ||
| .reset = rp2xxx.usb.ResetDriver(null, 0){}, | ||
| }, | ||
| )}) = .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, | ||
| }); | ||
|
|
||
| pub const panic = microzig.panic; | ||
|
|
||
| comptime { | ||
| _ = microzig.export_startup(); | ||
| } | ||
|
|
||
| const pin_config = microzig.board.pin_config; | ||
|
|
||
| var wakeup_deadline: ?Deadline = null; | ||
| fn on_suspend() void { | ||
| // try to wake up the host after 5 seconds. | ||
| wakeup_deadline = rp2xxx.time.deadline_in_ms(5 * std.time.ms_per_s); | ||
| } | ||
|
|
||
| fn on_resume() void { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add a context pointer to the callbacks please.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Is there a point in doing that? both are registered in
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It's a global variable in your example, but it may not be a global example in user code. |
||
| wakeup_deadline = null; | ||
| } | ||
|
|
||
| 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 led_deadline: Deadline = time.deadline_in_ms(500); | ||
|
|
||
| while (true) { | ||
| // You can now poll for USB events | ||
| usb_device.poll(&usb_controller); | ||
|
|
||
| if (wakeup_deadline) |deadline| { | ||
| if (deadline.is_reached_by(rp2xxx.time.get_time_since_boot())) { | ||
| // try to wake up the host | ||
| usb_controller.remote_wakeup(&usb_device.interface) catch |err| switch (err) { | ||
| error.NotSupported => unreachable, | ||
| error.NotEnabledByHost => { | ||
| std.log.warn("Host didn't enabled remote wakeup", .{}); | ||
| // on succesfull remote_wakeup it is guranteed that on_resume will be called | ||
| // but in the case of error.NotEnabledByHost let's disable it manually, so we don't spam the host | ||
| wakeup_deadline = null; | ||
| }, | ||
| error.NotConfigured => unreachable, // on_suspend guarantee that the controller is already configured | ||
| error.NotSuspended => unreachable, // the deadline is disabled in on_resume, so we whould never hit this | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| if (usb_controller.suspended()) { | ||
| // do something when the device is suspended | ||
| } | ||
|
|
||
| // Ensure that the host has finished enumerating our USB device | ||
| if (usb_controller.drivers()) |_| { | ||
| if (led_deadline.is_reached_by(time.get_time_since_boot())) { | ||
| led_deadline = time.deadline_in_ms(500); | ||
| pins.led.toggle(); | ||
| } | ||
| } | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not neccessary, you can just check if
signal_resumeis null