From 857424b7915ffaf00d03dc8d7e7639017e307b03 Mon Sep 17 00:00:00 2001 From: Andrew Leech Date: Thu, 3 Dec 2026 10:39:07 +1100 Subject: [PATCH 1/2] usb-device: Add WinUSB descriptor support. Signed-off-by: Andrew Leech --- .../usb/usb-device/examples/winusb_cdc.py | 105 ++++++++++++++++++ micropython/usb/usb-device/manifest.py | 2 +- .../usb/usb-device/tests/test_winusb.py | 54 +++++++++ micropython/usb/usb-device/usb/device/core.py | 26 ++++- .../usb/usb-device/usb/device/winusb.py | 74 ++++++++++++ 5 files changed, 259 insertions(+), 2 deletions(-) create mode 100644 micropython/usb/usb-device/examples/winusb_cdc.py create mode 100644 micropython/usb/usb-device/tests/test_winusb.py create mode 100644 micropython/usb/usb-device/usb/device/winusb.py diff --git a/micropython/usb/usb-device/examples/winusb_cdc.py b/micropython/usb/usb-device/examples/winusb_cdc.py new file mode 100644 index 0000000000..2f14e18469 --- /dev/null +++ b/micropython/usb/usb-device/examples/winusb_cdc.py @@ -0,0 +1,105 @@ +"""Composite CDC and WinUSB vendor interface that echoes bulk data. + +Install usb-device and use firmware with BOTH runtime USBDevice.config(desc_bos=...) +and USBDevice.config(vendor_control=True) support. BOS support alone does not +imply vendor forwarding. Configuration fails explicitly if either requested +keyword is unavailable. The board must provide a built-in CDC driver; +builtin_driver=True retains it. + +Assign a VID/PID owned by your project and use a GUID generated once for your +application. Reuse that GUID across devices/releases so host software can find +its DeviceInterfaceGUIDs interface. Omit guid to skip the registry property. +WinUSB's vendor_code must not collide with other device vendor requests. An +existing BOS can be supplied as desc_bos=; its capabilities are preserved. +An existing MS OS 2.0 capability is rejected to avoid advertising two handlers. +Interface descriptor builders may change their own state. If configuration +fails after a builder runs, activation is blocked until a configuration succeeds; +reconfigure or replace affected interface objects before reconnecting. +With BOS, the default bcdUSB is at least 0x0210; explicit values above +0x0200 are accepted for Windows BOS discovery. The composite MS OS 2.0 +configuration subset uses index 0 for the first configuration. Microsoft +MS OS 2.0 table 11 describes this field as a configuration value, but on +Windows 11 with an H5 CDC + WinUSB composite, value 1 produced Code 28 with no +interface GUID; changing only this field to 0 on a fresh device instance +bound WinUSB and exposed the GUID. + +This loopback is for full-speed USB only (64-byte bulk maximum packet size). +The vendor interface echoes bulk OUT data on bulk IN, one packet at a time. +The host should discover the endpoint addresses, write at most 64 bytes and +read the same number of bytes before sending the next packet. The device NAKs +OUT while the preceding echo is pending. Configuration is disconnected before +replacement. The GUID and VID/PID must be changed for a real product. +The OS 2.0 request is handled before device_control_xfer and interface callbacks. +An optional device_control_xfer(stage, request) callback returns None for an +unclaimed device-recipient vendor request, or False/True/a buffer under the same +rules as interface callbacks. Existing interface callbacks still handle their +requests. No Microsoft OS 1.0 descriptors are provided. +""" + +import usb.device +from usb.device.core import Interface +from usb.device.winusb import WinUSB + + +class VendorInterface(Interface): + def __init__(self): + super().__init__() + self.buffer = bytearray(64) + self.view = memoryview(self.buffer) + self.sent = 0 + self.received = 0 + + def num_eps(self): + return 1 # One endpoint number shared by IN and OUT. + + def desc_cfg(self, desc, itf_num, ep_num, strs): + self.ep_out = ep_num + self.ep_in = ep_num | 0x80 + desc.interface(itf_num, 2) + desc.endpoint(self.ep_out, "bulk", 64, 0) + desc.endpoint(self.ep_in, "bulk", 64, 0) + + def on_open(self): + super().on_open() + self._receive() + + def _receive(self): + if self.is_open(): + self.submit_xfer(self.ep_out, self.buffer, self._received) + + def _received(self, ep, result, count): + if not self.is_open(): + return + if result != 0: + self._receive() + return + self.sent = 0 + self.received = count + self.submit_xfer(self.ep_in, self.view[:count], self._sent) + + def _sent(self, ep, result, count): + if not self.is_open(): + return + if result == 0: + self.sent += count + if self.sent < self.received: + self.submit_xfer(self.ep_in, self.view[self.sent : self.received], self._sent) + else: + self._receive() + + def on_interface_control_xfer(self, stage, request): + if request[0] == 0xC1 and request[1] == 1: + return b"WinUSB example" if stage == 1 else True + return False + + +vendor = VendorInterface() +winusb = WinUSB(vendor, vendor_code=0x20, guid="{12345678-1234-5678-9ABC-DEF012345678}") +usb.device.get().init( + vendor, + builtin_driver=True, + device_class=0xEF, + device_subclass=0x02, + device_protocol=0x01, + winusb=winusb, +) diff --git a/micropython/usb/usb-device/manifest.py b/micropython/usb/usb-device/manifest.py index fa0d8a3f55..2607bd5436 100644 --- a/micropython/usb/usb-device/manifest.py +++ b/micropython/usb/usb-device/manifest.py @@ -1,2 +1,2 @@ -metadata(version="0.2.1") +metadata(version="0.2.2") package("usb") diff --git a/micropython/usb/usb-device/tests/test_winusb.py b/micropython/usb/usb-device/tests/test_winusb.py new file mode 100644 index 0000000000..d71777c5e4 --- /dev/null +++ b/micropython/usb/usb-device/tests/test_winusb.py @@ -0,0 +1,54 @@ +# Run from usb-device: micropython -m tests.test_winusb +import struct +from usb.device.winusb import WinUSB + +GUID = "{12345678-1234-5678-9ABC-DEF012345678}" +GUID_PROPERTY = struct.pack(" 2.0 device_class, # bDeviceClass device_subclass, # bDeviceSubClass device_protocol, # bDeviceProtocol @@ -233,6 +241,13 @@ def maybe_set(value, idx): max_power_ma, ) + options = {} + if desc_bos is not None: + options["desc_bos"] = desc_bos + if device_control_xfer is not None: + options["vendor_control"] = True + self._device_control_xfer = device_control_xfer + _usbd.config( desc_dev, desc.b, @@ -241,6 +256,7 @@ def maybe_set(value, idx): self._reset_cb, self._control_xfer_cb, self._xfer_cb, + **options, ) def active(self, *optional_value): @@ -356,6 +372,12 @@ def _control_xfer_cb(self, stage, request): wIndex = request[4] + (request[5] << 8) recipient, _, _ = split_bmRequestType(request[0]) + if recipient == _REQ_RECIPIENT_DEVICE and (request[0] & 0x60) == 0x40: + if self._device_control_xfer: + result = self._device_control_xfer(stage, request) + if result is not None: + return result + itf = None result = None @@ -374,6 +396,8 @@ def _control_xfer_cb(self, stage, request): result = itf.on_endpoint_control_xfer(stage, request) if not itf: + if (request[0] & 0x60) == 0x40: + return False # Unhandled vendor request # At time this code was written, only the control transfers shown # above are passed to the class driver callback. See # invoke_class_control() in tinyusb usbd.c diff --git a/micropython/usb/usb-device/usb/device/winusb.py b/micropython/usb/usb-device/usb/device/winusb.py new file mode 100644 index 0000000000..cc040c424b --- /dev/null +++ b/micropython/usb/usb-device/usb/device/winusb.py @@ -0,0 +1,74 @@ +# MIT license; Copyright (c) 2026 Andrew Leech +# +# Microsoft OS 2.0 descriptors that make Windows bind WinUSB to one interface. +# +# Pass desc_bos() and control_xfer to usb.device.get().init() as desc_bos= and +# device_control_xfer=, and set interface_number from the interface's desc_cfg(). +import struct + +_MS_OS_20_UUID = b"\xdf\x60\xdd\xd8\x89\x45\xc7\x4c\x9c\xd2\x65\x9d\x9e\x64\x8a\x9f" +_MS_OS_20_VERSION = 0x06030000 + + +def _utf16(value): + # Property names and GUIDs are ASCII. + return b"".join(struct.pack(" Date: Thu, 3 Dec 2026 10:51:00 +1100 Subject: [PATCH 2/2] usb-device: Add WinUSB host loopback examples. Signed-off-by: Andrew Leech --- .../usb/usb-device/examples/winusb_cdc.py | 50 ++++--------------- .../examples/winusb_host_windows.py | 47 +++++++++++++++++ 2 files changed, 56 insertions(+), 41 deletions(-) create mode 100644 micropython/usb/usb-device/examples/winusb_host_windows.py diff --git a/micropython/usb/usb-device/examples/winusb_cdc.py b/micropython/usb/usb-device/examples/winusb_cdc.py index 2f14e18469..6fab9248ef 100644 --- a/micropython/usb/usb-device/examples/winusb_cdc.py +++ b/micropython/usb/usb-device/examples/winusb_cdc.py @@ -1,39 +1,8 @@ """Composite CDC and WinUSB vendor interface that echoes bulk data. -Install usb-device and use firmware with BOTH runtime USBDevice.config(desc_bos=...) -and USBDevice.config(vendor_control=True) support. BOS support alone does not -imply vendor forwarding. Configuration fails explicitly if either requested -keyword is unavailable. The board must provide a built-in CDC driver; -builtin_driver=True retains it. - -Assign a VID/PID owned by your project and use a GUID generated once for your -application. Reuse that GUID across devices/releases so host software can find -its DeviceInterfaceGUIDs interface. Omit guid to skip the registry property. -WinUSB's vendor_code must not collide with other device vendor requests. An -existing BOS can be supplied as desc_bos=; its capabilities are preserved. -An existing MS OS 2.0 capability is rejected to avoid advertising two handlers. -Interface descriptor builders may change their own state. If configuration -fails after a builder runs, activation is blocked until a configuration succeeds; -reconfigure or replace affected interface objects before reconnecting. -With BOS, the default bcdUSB is at least 0x0210; explicit values above -0x0200 are accepted for Windows BOS discovery. The composite MS OS 2.0 -configuration subset uses index 0 for the first configuration. Microsoft -MS OS 2.0 table 11 describes this field as a configuration value, but on -Windows 11 with an H5 CDC + WinUSB composite, value 1 produced Code 28 with no -interface GUID; changing only this field to 0 on a fresh device instance -bound WinUSB and exposed the GUID. - -This loopback is for full-speed USB only (64-byte bulk maximum packet size). -The vendor interface echoes bulk OUT data on bulk IN, one packet at a time. -The host should discover the endpoint addresses, write at most 64 bytes and -read the same number of bytes before sending the next packet. The device NAKs -OUT while the preceding echo is pending. Configuration is disconnected before -replacement. The GUID and VID/PID must be changed for a real product. -The OS 2.0 request is handled before device_control_xfer and interface callbacks. -An optional device_control_xfer(stage, request) callback returns None for an -unclaimed device-recipient vendor request, or False/True/a buffer under the same -rules as interface callbacks. Existing interface callbacks still handle their -requests. No Microsoft OS 1.0 descriptors are provided. +Needs firmware with USBDevice.config(desc_bos=..., vendor_control=...) support. +Change the GUID and VID/PID for a real product. Run on the board with +"import winusb_cdc", then run winusb_host_windows.py on the host. """ import usb.device @@ -53,6 +22,7 @@ def num_eps(self): return 1 # One endpoint number shared by IN and OUT. def desc_cfg(self, desc, itf_num, ep_num, strs): + winusb.interface_number = itf_num self.ep_out = ep_num self.ep_in = ep_num | 0x80 desc.interface(itf_num, 2) @@ -87,19 +57,17 @@ def _sent(self, ep, result, count): else: self._receive() - def on_interface_control_xfer(self, stage, request): - if request[0] == 0xC1 and request[1] == 1: - return b"WinUSB example" if stage == 1 else True - return False - +# Interface GUID that Windows uses to name this device. Generate a unique one +# per product; {DEE824EF-729B-4A0E-9C14-B7117D33A817} fails to bind. +winusb = WinUSB(vendor_code=0x20, guid="{12345678-1234-5678-9ABC-DEF012345678}", composite=True) vendor = VendorInterface() -winusb = WinUSB(vendor, vendor_code=0x20, guid="{12345678-1234-5678-9ABC-DEF012345678}") usb.device.get().init( vendor, builtin_driver=True, device_class=0xEF, device_subclass=0x02, device_protocol=0x01, - winusb=winusb, + desc_bos=winusb.desc_bos(), + device_control_xfer=winusb.control_xfer, ) diff --git a/micropython/usb/usb-device/examples/winusb_host_windows.py b/micropython/usb/usb-device/examples/winusb_host_windows.py new file mode 100644 index 0000000000..fea218d0e4 --- /dev/null +++ b/micropython/usb/usb-device/examples/winusb_host_windows.py @@ -0,0 +1,47 @@ +"""Echo a packet through the vendor interface of winusb_cdc.py using WinUsbPy. + +Needs WinUsbPy: py -m pip install git+https://github.com/felHR85/WinUsbPy.git +Usage: py winusb_host_windows.py 0x1234 0x5678 +""" + +import sys +from ctypes import byref, c_ubyte, c_ulong, create_string_buffer + +from winusbpy import WinUsbPy +from winusbpy.winusbutils import WinUsb_ReadPipe, WinUsb_WritePipe + +vid, pid = (int(arg, 0) for arg in sys.argv[1:3]) + +# Windows lists any WinUSB device that has a GUID set, as winusb_cdc.py does. +api = WinUsbPy() +api.list_usb_devices(deviceinterface=True, present=True) +# WinUsbPy's find_device() cannot match a VID/PID; match it in the device path. +api.find_device = lambda name: "vid_%04x&pid_%04x" % (vid, pid) in api.device_paths[name].lower() +if not api.init_winusb_device(None, vid, pid): + sys.exit("WinUSB device not found") + +pipes = [api.query_pipe(i) for i in range(2)] +ep_in = next(p.pipe_id for p in pipes if p.pipe_id & 0x80) +ep_out = next(p.pipe_id for p in pipes if not p.pipe_id & 0x80) + +# WinUsbPy's read() and write() fail with the current WinUSB handle, so call WinUSB directly. +winusb = api.api.exec_function_winusb +data = b"Hello WinUSB!" +count = c_ulong() +if not winusb( + WinUsb_WritePipe, + api.handle_winusb, + c_ubyte(ep_out), + data, + c_ulong(len(data)), + byref(count), + None, +): + sys.exit("write failed") +buf = create_string_buffer(64) +if not winusb( + WinUsb_ReadPipe, api.handle_winusb, c_ubyte(ep_in), buf, c_ulong(64), byref(count), None +): + sys.exit("read failed") +print(buf.raw[: count.value]) +api.close_winusb_device()