Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions micropython/usb/usb-device/examples/winusb_cdc.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""Composite CDC and WinUSB vendor interface that echoes bulk data.

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
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):
winusb.interface_number = itf_num
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()


# 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()
usb.device.get().init(
vendor,
builtin_driver=True,
device_class=0xEF,
device_subclass=0x02,
device_protocol=0x01,
desc_bos=winusb.desc_bos(),
device_control_xfer=winusb.control_xfer,
)
47 changes: 47 additions & 0 deletions micropython/usb/usb-device/examples/winusb_host_windows.py
Original file line number Diff line number Diff line change
@@ -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()
2 changes: 1 addition & 1 deletion micropython/usb/usb-device/manifest.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
metadata(version="0.2.1")
metadata(version="0.2.2")
package("usb")
54 changes: 54 additions & 0 deletions micropython/usb/usb-device/tests/test_winusb.py
Original file line number Diff line number Diff line change
@@ -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("<HHHH", 10 + 42 + 80, 4, 7, 42) + b"".join(
struct.pack("<H", ord(c)) for c in "DeviceInterfaceGUIDs\0"
)
GUID_PROPERTY += struct.pack("<H", 80) + b"".join(struct.pack("<H", ord(c)) for c in GUID + "\0\0")
COMPATIBLE_ID = struct.pack("<HH8s8s", 20, 3, b"WINUSB", b"")

# Single function: header, compatible ID and GUID property.
winusb = WinUSB(guid=GUID)
expected = COMPATIBLE_ID + GUID_PROPERTY
assert (
winusb.descriptor_set()
== struct.pack("<HHIH", 10, 0, 0x06030000, 10 + len(expected)) + expected
)

# Composite: configuration subset 0 and function subset for the interface number.
winusb = WinUSB(guid=GUID, composite=True)
winusb.interface_number = 3
features = COMPATIBLE_ID + GUID_PROPERTY
function = struct.pack("<HHBBH", 8, 2, 3, 0, 8 + len(features))
config = struct.pack("<HHBBH", 8, 1, 0, 0, 16 + len(features))
expected = config + function + features
assert (
winusb.descriptor_set()
== struct.pack("<HHIH", 10, 0, 0x06030000, 10 + len(expected)) + expected
)

# The GUID is optional.
assert len(WinUSB().descriptor_set()) == 10 + len(COMPATIBLE_ID)

# BOS holds one platform capability that gives the set length and vendor code.
winusb = WinUSB(vendor_code=0x42, guid=GUID)
bos = winusb.desc_bos()
assert bos[:5] == struct.pack("<BBHB", 5, 15, len(bos), 1) and len(bos) == 33
assert bos[5:8] == bytes((28, 16, 5))
assert bos[9:25] == b"\xdf\x60\xdd\xd8\x89\x45\xc7\x4c\x9c\xd2\x65\x9d\x9e\x64\x8a\x9f"
assert struct.unpack("<IHB", bos[25:32]) == (0x06030000, len(winusb.descriptor_set()), 0x42)

# Only the descriptor set request is answered; anything else falls through.
request = struct.pack("<BBHHH", 0xC0, 0x42, 0, 7, 1000)
assert winusb.control_xfer(1, request) == winusb.descriptor_set()
assert winusb.control_xfer(2, request) is True
for other in (
struct.pack("<BBHHH", 0xC0, 0x43, 0, 7, 1000), # other vendor code
struct.pack("<BBHHH", 0xC0, 0x42, 0, 8, 1000), # other wIndex
struct.pack("<BBHHH", 0x40, 0x42, 0, 7, 0), # host to device
):
assert winusb.control_xfer(1, other) is None

print("WinUSB tests passed")
26 changes: 25 additions & 1 deletion micropython/usb/usb-device/usb/device/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ def __init__(self):
self._cb_thread = None # Thread currently running endpoint callback
self._cb_ep = None # Endpoint number currently running callback
self._usbd = machine.USBDevice() # low-level API
self._device_control_xfer = None

def init(self, *itfs, **kwargs):
# Helper function to configure the USB device and activate it in a single call
Expand All @@ -111,9 +112,16 @@ def config( # noqa: PLR0913
config_str=None,
max_power_ma=None,
remote_wakeup=False,
desc_bos=None,
device_control_xfer=None,
):
# Configure the USB device with a set of interfaces, and optionally reconfiguring the
# device and configuration descriptor fields
#
# desc_bos is a complete BOS descriptor. device_control_xfer(stage, request) is called
# for device-recipient vendor requests; it returns None to fall through to the
# interfaces, or the same results as Interface.on_device_control_xfer(). Both need
# firmware with USBDevice.config(desc_bos=..., vendor_control=...) support.

_usbd = self._usbd

Expand Down Expand Up @@ -147,7 +155,7 @@ def maybe_set(value, idx):
FMT,
f[0], # bLength
f[1], # bDescriptorType
f[2], # bcdUSB
max(f[2], 0x0210) if desc_bos is not None else f[2], # bcdUSB, BOS needs > 2.0
device_class, # bDeviceClass
device_subclass, # bDeviceSubClass
device_protocol, # bDeviceProtocol
Expand Down Expand Up @@ -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,
Expand All @@ -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):
Expand Down Expand Up @@ -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

Expand All @@ -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
Expand Down
74 changes: 74 additions & 0 deletions micropython/usb/usb-device/usb/device/winusb.py
Original file line number Diff line number Diff line change
@@ -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("<H", ord(c)) for c in value)


class WinUSB:
# vendor_code is the bRequest Windows uses to read the descriptor set.
# guid is a braced GUID string naming the interface for host software. Make it unique
# per product; {DEE824EF-729B-4A0E-9C14-B7117D33A817} fails to bind.
# composite must be True if the device has more than one function.
def __init__(self, vendor_code=0x20, guid=None, composite=False):
self.vendor_code = vendor_code
self.guid = guid
self.composite = composite
self.interface_number = 0 # First interface of the WinUSB function.
self._descriptor_set = None

def descriptor_set(self):
features = struct.pack("<HH8s8s", 20, 3, b"WINUSB", b"")
if self.guid:
name = _utf16("DeviceInterfaceGUIDs\0")
value = _utf16(self.guid + "\0\0")
features += (
struct.pack("<HHHH", 10 + len(name) + len(value), 4, 7, len(name))
+ name
+ struct.pack("<H", len(value))
+ value
)
if self.composite:
function = struct.pack("<HHBBH", 8, 2, self.interface_number, 0, 8 + len(features))
# Windows uses a zero-based configuration index here, although the
# specification names the field bConfigurationValue.
features = (
struct.pack("<HHBBH", 8, 1, 0, 0, 8 + len(function) + len(features))
+ function
+ features
)
return struct.pack("<HHIH", 10, 0, _MS_OS_20_VERSION, 10 + len(features)) + features

def desc_bos(self):
capability = struct.pack(
"<BBBB16sIHBB",
28,
16,
5,
0,
_MS_OS_20_UUID,
_MS_OS_20_VERSION,
len(self.descriptor_set()),
self.vendor_code,
0,
)
return struct.pack("<BBHB", 5, 15, 5 + len(capability), 1) + capability

def control_xfer(self, stage, request):
# Vendor, device-to-host, wIndex 7 (MS_OS_20_DESCRIPTOR_INDEX).
if request[0] != 0xC0 or request[1] != self.vendor_code or request[4] != 7:
return None
if stage == 1:
self._descriptor_set = self.descriptor_set() # Must stay alive for the transfer.
return self._descriptor_set
return True
Loading