python-can-gs-usb-fd 0.1.0__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-can-gs-usb-fd
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: python-can interface for CAN FD over gs_usb devices (tricore-debug-machine probe, candleLight FD)
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -23,7 +23,7 @@ Description-Content-Type: text/markdown
23
23
 
24
24
  # python-can-gs-usb-fd
25
25
 
26
- A [python-can](https://python-can.readthedocs.io/) interface for **CAN FD over gs_usb** devices: the tricore-debug-machine probe (USB 1d50:606f, interface 0) and other gs_usb devices that advertise CAN FD.
26
+ A [python-can](https://python-can.readthedocs.io/) interface for **CAN FD over gs_usb** devices: the tricore-debug-machine probe (USB 1d50:606f) and other gs_usb devices that advertise CAN FD.
27
27
 
28
28
  Installing the package registers the interface `gs_usb_fd` with python-can (entry point group `can.interface`). Code only needs `import can`, and every python-can tool (`can.logger`, `can.viewer`, `can.player`, ...) can use it.
29
29
 
@@ -31,31 +31,44 @@ Installing the package registers the interface `gs_usb_fd` with python-can (entr
31
31
 
32
32
  ## Installation
33
33
 
34
- In the repo's uv environment (`sw/`) it is already an editable workspace member:
35
-
36
34
  ```bash
37
- uv sync
35
+ pip install git+https://github.com/1atabey1/gs_usb_fd
36
+ # or, in a uv project:
37
+ uv add git+https://github.com/1atabey1/gs_usb_fd
38
38
  ```
39
39
 
40
- Elsewhere:
40
+ ### Windows
41
41
 
42
- ```bash
43
- pip install ./tools/python-can-gs-usb-fd
44
- ```
42
+ The device needs WinUSB on its gs_usb interface. The probe gets WinUSB automatically through MS OS 2.0 descriptors, so no driver install is needed.
43
+
44
+ The interface opens **only the gs_usb interface** it uses, directly through `winusb.dll` (found by candleLight's DeviceInterfaceGUID `{c15b4308-04d3-11e6-b3ea-6057189e6443}`). libusb would open the whole composite device instead, and WinUSB gives out one handle per interface, so a CAN program would lock every other program out of the probe's GDB, DAP and trace interfaces. Devices without that GUID (other drivers) fall back to libusb. `GS_USB_FD_BACKEND=libusb` forces libusb.
45
+
46
+ libusb-1.0 comes from the `libusb-package` dependency. Do **not** install libusb-win32: pyusb would fall back to its `libusb0.dll`, which cannot see WinUSB devices, and its filter driver can hang Windows device management.
45
47
 
46
- On Windows the device needs WinUSB on its gs_usb interface. The probe gets WinUSB automatically through MS OS 2.0 descriptors, so no driver install is needed. libusb-1.0 comes from the `libusb-package` dependency. Do **not** install libusb-win32: pyusb would fall back to its `libusb0.dll`, which cannot see WinUSB devices, and its filter driver can hang Windows device management.
48
+ ### Linux
49
+
50
+ pyusb and libusb-1.0. The kernel's `gs_usb` driver binds a probe's interface 0 (can0/can1); opening a bus here detaches it from the interface (until the probe is plugged in again). Your user needs access to the device node (the probe's udev rule).
47
51
 
48
52
  ## Configuration
49
53
 
50
54
  The interface is always `"gs_usb_fd"`. The `channel` is `"SERIAL@N"`, or just `N` for the first device found. Channels are **0-based**, as the device numbers them. On the probe, 0 is CAN1 (J4) and 1 is CAN2 (J5).
51
55
 
56
+ A device can have several gs_usb interfaces. Channels are then counted across them in interface order, so channel numbers do not depend on the layout. The probe has two USB layouts (`tdm_dap.py usb-mode`):
57
+
58
+ | Layout | gs_usb interfaces | Channel 0 | Channel 1 |
59
+ |---|---|---|---|
60
+ | `combined` (default) | 0 (2 channels) | interface 0, channel 0 | interface 0, channel 1 |
61
+ | `split` | 0 and 4 (1 channel each) | interface 0 | interface 4 |
62
+
63
+ In `split` two programs can each have one channel. In `combined` the program that opens the first channel holds both. An interface another program holds cannot be asked for its channel count, so it counts as one channel.
64
+
52
65
  ```python
53
66
  configs = can.detect_available_configs(interfaces=["gs_usb_fd"])
54
67
  # [{'interface': 'gs_usb_fd', 'channel': '290023001551333034363238@0'},
55
68
  # {'interface': 'gs_usb_fd', 'channel': '290023001551333034363238@1'}]
56
69
  ```
57
70
 
58
- Detection opens each device briefly, so devices that another process has open are skipped.
71
+ Detection opens each gs_usb interface briefly, so channels on an interface that another process has open are skipped.
59
72
 
60
73
  ## Opening a bus
61
74
 
@@ -94,7 +107,7 @@ Without `data_bitrate` and with a `can.BitTiming`, the channel runs classic CAN,
94
107
 
95
108
  ### Several channels
96
109
 
97
- Both channels of a device can be open at once, in one process: they share one USB connection and one reader thread that routes frames by channel.
110
+ Both channels of a device can be open at once, in one process. Channels on the same gs_usb interface share one USB connection and one reader thread that routes frames by channel. With the probe in its `split` layout, each channel can also go to a different process.
98
111
 
99
112
  ```python
100
113
  with (can.Bus(interface="gs_usb_fd", channel=0, timing=timing) as can1,
@@ -119,10 +132,10 @@ Both default to 1 Mbit/s / 5 Mbit/s (brp/tseg1/tseg2/sjw 5/12/3/3 and 2/5/2/2 at
119
132
  ## Tests
120
133
 
121
134
  ```bash
122
- uv run pytest tools/python-can-gs-usb-fd # a fake device, no hardware
123
- GS_USB_FD_HW=1 uv run pytest tools/python-can-gs-usb-fd -m hardware # on a probe: loopback and listen-only only
135
+ uv run --extra test pytest # a fake device, no hardware
136
+ GS_USB_FD_HW=1 uv run --extra test pytest -m hardware # on a probe: loopback and listen-only only
124
137
  ```
125
138
 
126
139
  ## Protocol
127
140
 
128
- The Linux gs_usb host format with CAN FD (`drivers/net/can/usb/gs_usb.c`, candleLight_fw). The probe's side is `Appli/usb/gs_usb.c`: BT_CONST_EXT, DATA_BITTIMING, frames of a 12-byte header plus 8 or 64 data bytes plus a 32-bit timestamp, and one frame per USB transfer.
141
+ The Linux gs_usb host format with CAN FD (`drivers/net/can/usb/gs_usb.c`, candleLight_fw). The probe's side is `sw/Appli/usb/gs_usb.c` in the tricore-debug-machine firmware: BT_CONST_EXT, DATA_BITTIMING, frames of a 12-byte header plus 8 or 64 data bytes plus a 32-bit timestamp, and one frame per USB transfer.
@@ -1,6 +1,6 @@
1
1
  # python-can-gs-usb-fd
2
2
 
3
- A [python-can](https://python-can.readthedocs.io/) interface for **CAN FD over gs_usb** devices: the tricore-debug-machine probe (USB 1d50:606f, interface 0) and other gs_usb devices that advertise CAN FD.
3
+ A [python-can](https://python-can.readthedocs.io/) interface for **CAN FD over gs_usb** devices: the tricore-debug-machine probe (USB 1d50:606f) and other gs_usb devices that advertise CAN FD.
4
4
 
5
5
  Installing the package registers the interface `gs_usb_fd` with python-can (entry point group `can.interface`). Code only needs `import can`, and every python-can tool (`can.logger`, `can.viewer`, `can.player`, ...) can use it.
6
6
 
@@ -8,31 +8,44 @@ Installing the package registers the interface `gs_usb_fd` with python-can (entr
8
8
 
9
9
  ## Installation
10
10
 
11
- In the repo's uv environment (`sw/`) it is already an editable workspace member:
12
-
13
11
  ```bash
14
- uv sync
12
+ pip install git+https://github.com/1atabey1/gs_usb_fd
13
+ # or, in a uv project:
14
+ uv add git+https://github.com/1atabey1/gs_usb_fd
15
15
  ```
16
16
 
17
- Elsewhere:
17
+ ### Windows
18
18
 
19
- ```bash
20
- pip install ./tools/python-can-gs-usb-fd
21
- ```
19
+ The device needs WinUSB on its gs_usb interface. The probe gets WinUSB automatically through MS OS 2.0 descriptors, so no driver install is needed.
20
+
21
+ The interface opens **only the gs_usb interface** it uses, directly through `winusb.dll` (found by candleLight's DeviceInterfaceGUID `{c15b4308-04d3-11e6-b3ea-6057189e6443}`). libusb would open the whole composite device instead, and WinUSB gives out one handle per interface, so a CAN program would lock every other program out of the probe's GDB, DAP and trace interfaces. Devices without that GUID (other drivers) fall back to libusb. `GS_USB_FD_BACKEND=libusb` forces libusb.
22
+
23
+ libusb-1.0 comes from the `libusb-package` dependency. Do **not** install libusb-win32: pyusb would fall back to its `libusb0.dll`, which cannot see WinUSB devices, and its filter driver can hang Windows device management.
22
24
 
23
- On Windows the device needs WinUSB on its gs_usb interface. The probe gets WinUSB automatically through MS OS 2.0 descriptors, so no driver install is needed. libusb-1.0 comes from the `libusb-package` dependency. Do **not** install libusb-win32: pyusb would fall back to its `libusb0.dll`, which cannot see WinUSB devices, and its filter driver can hang Windows device management.
25
+ ### Linux
26
+
27
+ pyusb and libusb-1.0. The kernel's `gs_usb` driver binds a probe's interface 0 (can0/can1); opening a bus here detaches it from the interface (until the probe is plugged in again). Your user needs access to the device node (the probe's udev rule).
24
28
 
25
29
  ## Configuration
26
30
 
27
31
  The interface is always `"gs_usb_fd"`. The `channel` is `"SERIAL@N"`, or just `N` for the first device found. Channels are **0-based**, as the device numbers them. On the probe, 0 is CAN1 (J4) and 1 is CAN2 (J5).
28
32
 
33
+ A device can have several gs_usb interfaces. Channels are then counted across them in interface order, so channel numbers do not depend on the layout. The probe has two USB layouts (`tdm_dap.py usb-mode`):
34
+
35
+ | Layout | gs_usb interfaces | Channel 0 | Channel 1 |
36
+ |---|---|---|---|
37
+ | `combined` (default) | 0 (2 channels) | interface 0, channel 0 | interface 0, channel 1 |
38
+ | `split` | 0 and 4 (1 channel each) | interface 0 | interface 4 |
39
+
40
+ In `split` two programs can each have one channel. In `combined` the program that opens the first channel holds both. An interface another program holds cannot be asked for its channel count, so it counts as one channel.
41
+
29
42
  ```python
30
43
  configs = can.detect_available_configs(interfaces=["gs_usb_fd"])
31
44
  # [{'interface': 'gs_usb_fd', 'channel': '290023001551333034363238@0'},
32
45
  # {'interface': 'gs_usb_fd', 'channel': '290023001551333034363238@1'}]
33
46
  ```
34
47
 
35
- Detection opens each device briefly, so devices that another process has open are skipped.
48
+ Detection opens each gs_usb interface briefly, so channels on an interface that another process has open are skipped.
36
49
 
37
50
  ## Opening a bus
38
51
 
@@ -71,7 +84,7 @@ Without `data_bitrate` and with a `can.BitTiming`, the channel runs classic CAN,
71
84
 
72
85
  ### Several channels
73
86
 
74
- Both channels of a device can be open at once, in one process: they share one USB connection and one reader thread that routes frames by channel.
87
+ Both channels of a device can be open at once, in one process. Channels on the same gs_usb interface share one USB connection and one reader thread that routes frames by channel. With the probe in its `split` layout, each channel can also go to a different process.
75
88
 
76
89
  ```python
77
90
  with (can.Bus(interface="gs_usb_fd", channel=0, timing=timing) as can1,
@@ -96,10 +109,10 @@ Both default to 1 Mbit/s / 5 Mbit/s (brp/tseg1/tseg2/sjw 5/12/3/3 and 2/5/2/2 at
96
109
  ## Tests
97
110
 
98
111
  ```bash
99
- uv run pytest tools/python-can-gs-usb-fd # a fake device, no hardware
100
- GS_USB_FD_HW=1 uv run pytest tools/python-can-gs-usb-fd -m hardware # on a probe: loopback and listen-only only
112
+ uv run --extra test pytest # a fake device, no hardware
113
+ GS_USB_FD_HW=1 uv run --extra test pytest -m hardware # on a probe: loopback and listen-only only
101
114
  ```
102
115
 
103
116
  ## Protocol
104
117
 
105
- The Linux gs_usb host format with CAN FD (`drivers/net/can/usb/gs_usb.c`, candleLight_fw). The probe's side is `Appli/usb/gs_usb.c`: BT_CONST_EXT, DATA_BITTIMING, frames of a 12-byte header plus 8 or 64 data bytes plus a 32-bit timestamp, and one frame per USB transfer.
118
+ The Linux gs_usb host format with CAN FD (`drivers/net/can/usb/gs_usb.c`, candleLight_fw). The probe's side is `sw/Appli/usb/gs_usb.c` in the tricore-debug-machine firmware: BT_CONST_EXT, DATA_BITTIMING, frames of a 12-byte header plus 8 or 64 data bytes plus a 32-bit timestamp, and one frame per USB transfer.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "python-can-gs-usb-fd"
3
- version = "0.1.0"
3
+ version = "0.2.0"
4
4
  description = "python-can interface for CAN FD over gs_usb devices (tricore-debug-machine probe, candleLight FD)"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "python-can-gs-usb-fd"
3
- version = "0.1.0"
3
+ version = "0.2.0"
4
4
  description = "python-can interface for CAN FD over gs_usb devices (tricore-debug-machine probe, candleLight FD)"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -8,4 +8,4 @@ without importing anything from here.
8
8
  from .bus import INTERFACE, GsUsbFdBus, parse_channel
9
9
 
10
10
  __all__ = ["INTERFACE", "GsUsbFdBus", "parse_channel"]
11
- __version__ = "0.1.0"
11
+ __version__ = "0.2.0"
@@ -0,0 +1,371 @@
1
+ """One interface of a composite USB device through WinUSB (Windows only).
2
+
3
+ (The same module as mcds_trace.winusb in the tricore-debug-machine repository.)
4
+
5
+ libusb opens a composite WinUSB device as a whole: it takes every interface's
6
+ WinUSB handle, and WinUSB gives out one handle per interface, so the first
7
+ program to open a device locks every other one out of all of its interfaces
8
+ - a CAN tool out of a debug interface, a debugger out of CAN. This module opens only the
9
+ interface asked for: it finds the interface's own device path by its
10
+ DeviceInterfaceGUID (which the probe's MS OS 2.0 descriptors register) and
11
+ talks to it through winusb.dll. Another program can hold any other
12
+ interface meanwhile.
13
+
14
+ `WinUsbInterface` reads and writes like a pyusb Device, so code written
15
+ against pyusb runs on it unchanged: read(ep, size_or_buffer, timeout),
16
+ write(ep, data, timeout) and ctrl_transfer(...), raising pyusb's
17
+ USBTimeoutError / USBError. All I/O is overlapped, so one thread may wait on
18
+ an endpoint while another uses a different one.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import array
24
+ import ctypes
25
+ import re
26
+ import sys
27
+ import uuid
28
+ from dataclasses import dataclass
29
+
30
+ try: # pyusb's exception types, so callers keep catching what they catch
31
+ from usb.core import USBError, USBTimeoutError
32
+ except ImportError: # pragma: no cover
33
+ class USBError(IOError):
34
+ def __init__(self, strerror, error_code=None, errno=None):
35
+ IOError.__init__(self, errno, strerror)
36
+ self.backend_error_code = error_code
37
+
38
+ class USBTimeoutError(USBError):
39
+ pass
40
+
41
+ AVAILABLE = sys.platform == 'win32'
42
+
43
+ ERROR_ACCESS_DENIED = 5
44
+ ERROR_IO_PENDING = 997
45
+ ERROR_OPERATION_ABORTED = 995
46
+ ERROR_SEM_TIMEOUT = 121
47
+ WAIT_OBJECT_0, WAIT_TIMEOUT = 0, 0x102
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class InterfacePath:
52
+ path: str # the interface's device path, for CreateFile
53
+ serial: str # the device's iSerialNumber (from its instance ID)
54
+ vid: int
55
+ pid: int
56
+ interface: int # bInterfaceNumber (from "&mi_NN"), -1 if not composite
57
+
58
+
59
+ if AVAILABLE:
60
+ from ctypes import wintypes as wt # Windows only (fails on some other platforms)
61
+
62
+ _ULONG_PTR = ctypes.c_size_t
63
+
64
+ class _GUID(ctypes.Structure):
65
+ _fields_ = [('Data1', wt.DWORD), ('Data2', wt.WORD), ('Data3', wt.WORD),
66
+ ('Data4', ctypes.c_ubyte * 8)]
67
+
68
+ class _SP_DEVICE_INTERFACE_DATA(ctypes.Structure):
69
+ _fields_ = [('cbSize', wt.DWORD), ('InterfaceClassGuid', _GUID), ('Flags', wt.DWORD),
70
+ ('Reserved', _ULONG_PTR)]
71
+
72
+ class _SP_DEVINFO_DATA(ctypes.Structure):
73
+ _fields_ = [('cbSize', wt.DWORD), ('ClassGuid', _GUID), ('DevInst', wt.DWORD),
74
+ ('Reserved', _ULONG_PTR)]
75
+
76
+ class _OVERLAPPED(ctypes.Structure):
77
+ _fields_ = [('Internal', _ULONG_PTR), ('InternalHigh', _ULONG_PTR), ('Offset', wt.DWORD),
78
+ ('OffsetHigh', wt.DWORD), ('hEvent', wt.HANDLE)]
79
+
80
+ class _SETUP(ctypes.Structure):
81
+ _pack_ = 1
82
+ _fields_ = [('RequestType', ctypes.c_ubyte), ('Request', ctypes.c_ubyte),
83
+ ('Value', ctypes.c_ushort), ('Index', ctypes.c_ushort),
84
+ ('Length', ctypes.c_ushort)]
85
+
86
+ _k32 = ctypes.WinDLL('kernel32', use_last_error=True)
87
+ _setupapi = ctypes.WinDLL('setupapi', use_last_error=True)
88
+ _cfgmgr = ctypes.WinDLL('cfgmgr32', use_last_error=True)
89
+ _winusb = ctypes.WinDLL('winusb', use_last_error=True)
90
+
91
+ _INVALID_HANDLE = ctypes.c_void_p(-1).value
92
+
93
+ def _proto(fn, res, *args):
94
+ fn.restype = res
95
+ fn.argtypes = args
96
+ return fn
97
+
98
+ _GetClassDevs = _proto(_setupapi.SetupDiGetClassDevsW, ctypes.c_void_p,
99
+ ctypes.POINTER(_GUID), wt.LPCWSTR, wt.HWND, wt.DWORD)
100
+ _EnumIfaces = _proto(_setupapi.SetupDiEnumDeviceInterfaces, wt.BOOL, ctypes.c_void_p,
101
+ ctypes.c_void_p, ctypes.POINTER(_GUID), wt.DWORD,
102
+ ctypes.POINTER(_SP_DEVICE_INTERFACE_DATA))
103
+ _IfaceDetail = _proto(_setupapi.SetupDiGetDeviceInterfaceDetailW, wt.BOOL, ctypes.c_void_p,
104
+ ctypes.POINTER(_SP_DEVICE_INTERFACE_DATA), ctypes.c_void_p, wt.DWORD,
105
+ ctypes.POINTER(wt.DWORD), ctypes.POINTER(_SP_DEVINFO_DATA))
106
+ _DestroyList = _proto(_setupapi.SetupDiDestroyDeviceInfoList, wt.BOOL, ctypes.c_void_p)
107
+ _CM_Get_Parent = _proto(_cfgmgr.CM_Get_Parent, wt.DWORD, ctypes.POINTER(wt.DWORD), wt.DWORD,
108
+ wt.ULONG)
109
+ _CM_Get_Device_ID = _proto(_cfgmgr.CM_Get_Device_IDW, wt.DWORD, wt.DWORD, wt.LPWSTR, wt.ULONG,
110
+ wt.ULONG)
111
+ _CreateFile = _proto(_k32.CreateFileW, ctypes.c_void_p, wt.LPCWSTR, wt.DWORD, wt.DWORD,
112
+ ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE)
113
+ _CloseHandle = _proto(_k32.CloseHandle, wt.BOOL, ctypes.c_void_p)
114
+ _CreateEvent = _proto(_k32.CreateEventW, ctypes.c_void_p, ctypes.c_void_p, wt.BOOL, wt.BOOL,
115
+ wt.LPCWSTR)
116
+ _Wait = _proto(_k32.WaitForSingleObject, wt.DWORD, ctypes.c_void_p, wt.DWORD)
117
+ _CancelIoEx = _proto(_k32.CancelIoEx, wt.BOOL, ctypes.c_void_p, ctypes.POINTER(_OVERLAPPED))
118
+
119
+ _WU_Initialize = _proto(_winusb.WinUsb_Initialize, wt.BOOL, ctypes.c_void_p,
120
+ ctypes.POINTER(ctypes.c_void_p))
121
+ _WU_Free = _proto(_winusb.WinUsb_Free, wt.BOOL, ctypes.c_void_p)
122
+ _WU_ReadPipe = _proto(_winusb.WinUsb_ReadPipe, wt.BOOL, ctypes.c_void_p, ctypes.c_ubyte,
123
+ ctypes.c_void_p, wt.ULONG, ctypes.POINTER(wt.ULONG),
124
+ ctypes.POINTER(_OVERLAPPED))
125
+ _WU_WritePipe = _proto(_winusb.WinUsb_WritePipe, wt.BOOL, ctypes.c_void_p, ctypes.c_ubyte,
126
+ ctypes.c_void_p, wt.ULONG, ctypes.POINTER(wt.ULONG),
127
+ ctypes.POINTER(_OVERLAPPED))
128
+ _WU_Control = _proto(_winusb.WinUsb_ControlTransfer, wt.BOOL, ctypes.c_void_p, _SETUP,
129
+ ctypes.c_void_p, wt.ULONG, ctypes.POINTER(wt.ULONG),
130
+ ctypes.POINTER(_OVERLAPPED))
131
+ _WU_Result = _proto(_winusb.WinUsb_GetOverlappedResult, wt.BOOL, ctypes.c_void_p,
132
+ ctypes.POINTER(_OVERLAPPED), ctypes.POINTER(wt.DWORD), wt.BOOL)
133
+ _WU_ResetPipe = _proto(_winusb.WinUsb_ResetPipe, wt.BOOL, ctypes.c_void_p, ctypes.c_ubyte)
134
+ _WU_FlushPipe = _proto(_winusb.WinUsb_FlushPipe, wt.BOOL, ctypes.c_void_p, ctypes.c_ubyte)
135
+ _WU_GetDescriptor = _proto(_winusb.WinUsb_GetDescriptor, wt.BOOL, ctypes.c_void_p,
136
+ ctypes.c_ubyte, ctypes.c_ubyte, ctypes.c_ushort, ctypes.c_void_p,
137
+ wt.ULONG, ctypes.POINTER(wt.ULONG))
138
+
139
+ class _IF_DESC(ctypes.Structure):
140
+ _pack_ = 1
141
+ _fields_ = [('bLength', ctypes.c_ubyte), ('bDescriptorType', ctypes.c_ubyte),
142
+ ('bInterfaceNumber', ctypes.c_ubyte), ('bAlternateSetting', ctypes.c_ubyte),
143
+ ('bNumEndpoints', ctypes.c_ubyte), ('bInterfaceClass', ctypes.c_ubyte),
144
+ ('bInterfaceSubClass', ctypes.c_ubyte), ('bInterfaceProtocol', ctypes.c_ubyte),
145
+ ('iInterface', ctypes.c_ubyte)]
146
+
147
+ class _PIPE_INFO(ctypes.Structure):
148
+ _fields_ = [('PipeType', ctypes.c_int), ('PipeId', ctypes.c_ubyte),
149
+ ('MaximumPacketSize', ctypes.c_ushort), ('Interval', ctypes.c_ubyte)]
150
+
151
+ _WU_QuerySettings = _proto(_winusb.WinUsb_QueryInterfaceSettings, wt.BOOL, ctypes.c_void_p,
152
+ ctypes.c_ubyte, ctypes.POINTER(_IF_DESC))
153
+ _WU_QueryPipe = _proto(_winusb.WinUsb_QueryPipe, wt.BOOL, ctypes.c_void_p, ctypes.c_ubyte,
154
+ ctypes.c_ubyte, ctypes.POINTER(_PIPE_INFO))
155
+
156
+
157
+ def _guid(s: str):
158
+ u = uuid.UUID(s)
159
+ g = _GUID()
160
+ g.Data1, g.Data2, g.Data3 = u.fields[0], u.fields[1], u.fields[2]
161
+ g.Data4[:] = list(u.bytes[8:])
162
+ return g
163
+
164
+
165
+ _ID_RE = re.compile(r'VID_([0-9A-F]{4})&PID_([0-9A-F]{4})\\(.*)$', re.I)
166
+ _MI_RE = re.compile(r'&mi_([0-9a-f]{2})', re.I)
167
+
168
+
169
+ def _device_id(devinst: int) -> str:
170
+ buf = ctypes.create_unicode_buffer(512)
171
+ if _CM_Get_Device_ID(devinst, buf, len(buf), 0) != 0:
172
+ return ''
173
+ return buf.value
174
+
175
+
176
+ def list_interfaces(guid: str, vid: int | None = None, pid: int | None = None) -> list[InterfacePath]:
177
+ """The present interfaces registered under DeviceInterfaceGUID guid,
178
+ optionally only those of vid:pid, sorted by serial and interface."""
179
+ if not AVAILABLE:
180
+ return []
181
+ g = _guid(guid)
182
+ h = _GetClassDevs(ctypes.byref(g), None, None, 0x02 | 0x10) # PRESENT | DEVICEINTERFACE
183
+ if h is None or h == _INVALID_HANDLE:
184
+ return []
185
+ out = []
186
+ try:
187
+ k = 0
188
+ while True:
189
+ ifd = _SP_DEVICE_INTERFACE_DATA()
190
+ ifd.cbSize = ctypes.sizeof(ifd)
191
+ if not _EnumIfaces(h, None, ctypes.byref(g), k, ctypes.byref(ifd)):
192
+ break
193
+ k += 1
194
+ need = wt.DWORD(0)
195
+ _IfaceDetail(h, ctypes.byref(ifd), None, 0, ctypes.byref(need), None)
196
+ if not need.value:
197
+ continue
198
+ raw = ctypes.create_string_buffer(need.value)
199
+ # SP_DEVICE_INTERFACE_DETAIL_DATA_W: cbSize is the fixed part (8 on 64-bit)
200
+ ctypes.cast(raw, ctypes.POINTER(wt.DWORD))[0] = 8 if ctypes.sizeof(ctypes.c_void_p) == 8 else 6
201
+ dev = _SP_DEVINFO_DATA()
202
+ dev.cbSize = ctypes.sizeof(dev)
203
+ if not _IfaceDetail(h, ctypes.byref(ifd), raw, need, None, ctypes.byref(dev)):
204
+ continue
205
+ path = ctypes.wstring_at(ctypes.addressof(raw) + 4)
206
+ mi = _MI_RE.search(path)
207
+ # the device (not interface) instance ID ends in the serial: a
208
+ # composite function's parent is the device
209
+ ident = _device_id(dev.DevInst)
210
+ if mi:
211
+ parent = wt.DWORD(0)
212
+ if _CM_Get_Parent(ctypes.byref(parent), dev.DevInst, 0) == 0:
213
+ ident = _device_id(parent.value)
214
+ m = _ID_RE.search(ident)
215
+ if not m:
216
+ continue
217
+ v, p, serial = int(m.group(1), 16), int(m.group(2), 16), m.group(3)
218
+ if (vid is not None and v != vid) or (pid is not None and p != pid):
219
+ continue
220
+ out.append(InterfacePath(path, serial, v, p, int(mi.group(1), 16) if mi else -1))
221
+ finally:
222
+ _DestroyList(h)
223
+ return sorted(out, key=lambda x: (x.serial, x.interface))
224
+
225
+
226
+ class WinUsbInterface:
227
+ """An open WinUSB interface, with pyusb Device-style I/O."""
228
+
229
+ def __init__(self, where: InterfacePath | str):
230
+ if not AVAILABLE:
231
+ raise USBError('WinUSB is Windows only')
232
+ self.info = where if isinstance(where, InterfacePath) else None
233
+ path = where.path if isinstance(where, InterfacePath) else where
234
+ self.serial_number = self.info.serial if self.info else None
235
+ self._file = _CreateFile(path, 0xC0000000, 0x3, None, 3, 0x80 | 0x40000000, None)
236
+ if self._file is None or self._file == _INVALID_HANDLE:
237
+ err = ctypes.get_last_error()
238
+ if err == ERROR_ACCESS_DENIED:
239
+ raise USBError('interface busy: another program has it open', err, 16)
240
+ raise USBError('cannot open %s (Windows error %d)' % (path, err), err)
241
+ self._h = ctypes.c_void_p()
242
+ if not _WU_Initialize(self._file, ctypes.byref(self._h)):
243
+ err = ctypes.get_last_error()
244
+ _CloseHandle(self._file)
245
+ self._file = None
246
+ raise USBError('WinUsb_Initialize failed (Windows error %d)' % err, err)
247
+
248
+ # -- lifetime -----------------------------------------------------------------
249
+
250
+ def close(self) -> None:
251
+ if getattr(self, '_h', None) and self._h.value:
252
+ _WU_Free(self._h)
253
+ self._h = ctypes.c_void_p()
254
+ if getattr(self, '_file', None):
255
+ _CloseHandle(self._file)
256
+ self._file = None
257
+
258
+ def __enter__(self) -> 'WinUsbInterface':
259
+ return self
260
+
261
+ def __exit__(self, *exc) -> None:
262
+ self.close()
263
+
264
+ def __del__(self):
265
+ try:
266
+ self.close()
267
+ except Exception:
268
+ pass
269
+
270
+ # -- I/O ----------------------------------------------------------------------
271
+
272
+ def _io(self, start, timeout: int | None) -> int:
273
+ """Run one overlapped operation start(ov) to completion; the bytes
274
+ moved. A timeout cancels it: what arrived before counts, nothing
275
+ arrived raises USBTimeoutError."""
276
+ if not self._h.value:
277
+ raise USBError('interface closed')
278
+ ov = _OVERLAPPED()
279
+ ov.hEvent = _CreateEvent(None, True, False, None)
280
+ try:
281
+ if not start(ctypes.byref(ov)):
282
+ err = ctypes.get_last_error()
283
+ if err != ERROR_IO_PENDING:
284
+ raise USBError('USB transfer failed (Windows error %d)' % err, err)
285
+ ms = 0xFFFFFFFF if not timeout else int(timeout)
286
+ timed_out = _Wait(ov.hEvent, ms) == WAIT_TIMEOUT
287
+ if timed_out:
288
+ _CancelIoEx(self._file, ctypes.byref(ov))
289
+ n = wt.DWORD(0)
290
+ ok = _WU_Result(self._h, ctypes.byref(ov), ctypes.byref(n), True)
291
+ if not ok:
292
+ err = ctypes.get_last_error()
293
+ if n.value:
294
+ return n.value
295
+ if timed_out or err in (ERROR_OPERATION_ABORTED, ERROR_SEM_TIMEOUT):
296
+ raise USBTimeoutError('Operation timed out', err, 110)
297
+ raise USBError('USB transfer failed (Windows error %d)' % err, err)
298
+ return n.value
299
+ finally:
300
+ _CloseHandle(ov.hEvent)
301
+
302
+ def read(self, endpoint: int, size_or_buffer, timeout: int | None = None):
303
+ """pyusb's Device.read: an array('B') of what arrived, or, given a
304
+ buffer, the count read into it."""
305
+ if isinstance(size_or_buffer, int):
306
+ buf = array.array('B', bytes(size_or_buffer))
307
+ n = self._read_into(endpoint, buf, timeout)
308
+ return buf[:n]
309
+ return self._read_into(endpoint, size_or_buffer, timeout)
310
+
311
+ def _read_into(self, endpoint, buf, timeout) -> int:
312
+ n = len(buf) * getattr(buf, 'itemsize', 1)
313
+ c = (ctypes.c_ubyte * n).from_buffer(buf)
314
+ return self._io(lambda ov: _WU_ReadPipe(self._h, endpoint | 0x80, c, n, None, ov), timeout)
315
+
316
+ def write(self, endpoint: int, data, timeout: int | None = None) -> int:
317
+ b = bytes(data)
318
+ c = ctypes.create_string_buffer(b, len(b))
319
+ return self._io(lambda ov: _WU_WritePipe(self._h, endpoint & 0x7F, c, len(b), None, ov),
320
+ timeout)
321
+
322
+ def ctrl_transfer(self, bmRequestType: int, bRequest: int, wValue: int = 0, wIndex: int = 0,
323
+ data_or_wLength=None, timeout: int | None = None):
324
+ """pyusb's Device.ctrl_transfer: IN returns an array('B'), OUT the
325
+ count written. WinUSB puts the interface's own number in wIndex for
326
+ interface requests."""
327
+ if bmRequestType & 0x80:
328
+ n = int(data_or_wLength or 0)
329
+ buf = (ctypes.c_ubyte * max(n, 1))()
330
+ else:
331
+ b = bytes(data_or_wLength or b'')
332
+ n = len(b)
333
+ buf = (ctypes.c_ubyte * max(n, 1)).from_buffer_copy(b or b'\0')
334
+ setup = _SETUP(bmRequestType, bRequest, wValue & 0xFFFF, wIndex & 0xFFFF, n)
335
+ got = self._io(lambda ov: _WU_Control(self._h, setup, buf, n, None, ov), timeout)
336
+ if bmRequestType & 0x80:
337
+ return array.array('B', bytes(buf)[:got])
338
+ return got
339
+
340
+ def clear_halt(self, endpoint: int) -> None:
341
+ _WU_ResetPipe(self._h, endpoint)
342
+
343
+ def flush(self, endpoint: int) -> None:
344
+ """Drop what WinUSB buffered for an IN endpoint."""
345
+ _WU_FlushPipe(self._h, endpoint | 0x80)
346
+
347
+ def string(self, index: int, langid: int = 0x0409) -> str:
348
+ buf = (ctypes.c_ubyte * 256)()
349
+ n = wt.ULONG(0)
350
+ if not index or not _WU_GetDescriptor(self._h, 3, index, langid, buf, 256, ctypes.byref(n)):
351
+ return ''
352
+ return bytes(buf)[2:n.value].decode('utf-16-le', errors='replace')
353
+
354
+ def pipes(self) -> list[tuple[int, int, int]]:
355
+ """The interface's endpoints: (address, type 0..3, max packet size)."""
356
+ d = _IF_DESC()
357
+ if not _WU_QuerySettings(self._h, 0, ctypes.byref(d)):
358
+ raise USBError('no interface settings (Windows error %d)' % ctypes.get_last_error())
359
+ out = []
360
+ for k in range(d.bNumEndpoints):
361
+ pi = _PIPE_INFO()
362
+ if _WU_QueryPipe(self._h, 0, k, ctypes.byref(pi)):
363
+ out.append((pi.PipeId, pi.PipeType, pi.MaximumPacketSize))
364
+ return out
365
+
366
+ def device_descriptor(self) -> bytes:
367
+ buf = (ctypes.c_ubyte * 18)()
368
+ n = wt.ULONG(0)
369
+ if not _WU_GetDescriptor(self._h, 1, 0, 0, buf, 18, ctypes.byref(n)):
370
+ raise USBError('no device descriptor (Windows error %d)' % ctypes.get_last_error())
371
+ return bytes(buf)[:n.value]