File: usb_probe.py

package info (click to toggle)
python-bumble 0.0.220-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 9,280 kB
  • sloc: python: 71,701; java: 3,782; javascript: 823; xml: 203; sh: 172; makefile: 8
file content (276 lines) | stat: -rw-r--r-- 10,313 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# Copyright 2021-2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# -----------------------------------------------------------------------------
# This tool lists all the USB devices, with details about each device.
# For each device, the different possible Bumble transport strings that can
# refer to it are listed. If the device is known to be a Bluetooth HCI device,
# its identifier is printed in reverse colors, and the transport names in cyan color.
# For other devices, regardless of their type, the transport names are printed
# in red. Whether that device is actually a Bluetooth device or not depends on
# whether it is a Bluetooth device that uses a non-standard Class, or some other
# type of device (there's no way to tell).
# -----------------------------------------------------------------------------

# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
import click
import usb1

import bumble.logging
from bumble.colors import color
from bumble.transport.usb import load_libusb

# -----------------------------------------------------------------------------
# Constants
# -----------------------------------------------------------------------------
USB_DEVICE_CLASS_DEVICE = 0x00
USB_DEVICE_CLASS_WIRELESS_CONTROLLER = 0xE0
USB_DEVICE_SUBCLASS_RF_CONTROLLER = 0x01
USB_DEVICE_PROTOCOL_BLUETOOTH_PRIMARY_CONTROLLER = 0x01

USB_DEVICE_CLASSES = {
    0x00: 'Device',
    0x01: 'Audio',
    0x02: 'Communications and CDC Control',
    0x03: 'Human Interface Device',
    0x05: 'Physical',
    0x06: 'Still Imaging',
    0x07: 'Printer',
    0x08: 'Mass Storage',
    0x09: 'Hub',
    0x0A: 'CDC Data',
    0x0B: 'Smart Card',
    0x0D: 'Content Security',
    0x0E: 'Video',
    0x0F: 'Personal Healthcare',
    0x10: 'Audio/Video',
    0x11: 'Billboard',
    0x12: 'USB Type-C Bridge',
    0x3C: 'I3C',
    0xDC: 'Diagnostic',
    USB_DEVICE_CLASS_WIRELESS_CONTROLLER: (
        'Wireless Controller',
        {
            0x01: {
                0x01: 'Bluetooth',
                0x02: 'UWB',
                0x03: 'Remote NDIS',
                0x04: 'Bluetooth AMP',
            }
        },
    ),
    0xEF: 'Miscellaneous',
    0xFE: 'Application Specific',
    0xFF: 'Vendor Specific',
}

USB_ENDPOINT_IN = 0x80
USB_ENDPOINT_TYPES = ['CONTROL', 'ISOCHRONOUS', 'BULK', 'INTERRUPT']

USB_BT_HCI_CLASS_TUPLE = (
    USB_DEVICE_CLASS_WIRELESS_CONTROLLER,
    USB_DEVICE_SUBCLASS_RF_CONTROLLER,
    USB_DEVICE_PROTOCOL_BLUETOOTH_PRIMARY_CONTROLLER,
)


# -----------------------------------------------------------------------------
def show_device_details(device):
    for configuration in device:
        print(f'  Configuration {configuration.getConfigurationValue()}')
        for interface in configuration:
            for setting in interface:
                alternate_setting = setting.getAlternateSetting()
                suffix = (
                    f'/{alternate_setting}' if interface.getNumSettings() > 1 else ''
                )
                (class_string, subclass_string) = get_class_info(
                    setting.getClass(), setting.getSubClass(), setting.getProtocol()
                )
                details = f'({class_string}, {subclass_string})'
                print(f'      Interface: {setting.getNumber()}{suffix} {details}')
                for endpoint in setting:
                    endpoint_type = USB_ENDPOINT_TYPES[endpoint.getAttributes() & 3]
                    endpoint_direction = (
                        'OUT'
                        if (endpoint.getAddress() & USB_ENDPOINT_IN == 0)
                        else 'IN'
                    )
                    print(
                        f'        Endpoint 0x{endpoint.getAddress():02X}: '
                        f'{endpoint_type} {endpoint_direction}'
                    )


# -----------------------------------------------------------------------------
def get_class_info(cls, subclass, protocol):
    class_info = USB_DEVICE_CLASSES.get(cls)
    protocol_string = ''
    if class_info is None:
        class_string = f'0x{cls:02X}'
    else:
        if isinstance(class_info, tuple):
            class_string = class_info[0]
            subclass_info = class_info[1].get(subclass)
            if subclass_info:
                protocol_string = subclass_info.get(protocol)
                if protocol_string is not None:
                    protocol_string = f' [{protocol_string}]'

        else:
            class_string = class_info

    subclass_string = f'{subclass}/{protocol}{protocol_string}'

    return (class_string, subclass_string)


# -----------------------------------------------------------------------------
def is_bluetooth_hci(device):
    # Check if the device class indicates a match
    if (
        device.getDeviceClass(),
        device.getDeviceSubClass(),
        device.getDeviceProtocol(),
    ) == USB_BT_HCI_CLASS_TUPLE:
        return True

    # If the device class is 'Device', look for a matching interface
    if device.getDeviceClass() == USB_DEVICE_CLASS_DEVICE:
        for configuration in device:
            for interface in configuration:
                for setting in interface:
                    if (
                        setting.getClass(),
                        setting.getSubClass(),
                        setting.getProtocol(),
                    ) == USB_BT_HCI_CLASS_TUPLE:
                        return True

    return False


# -----------------------------------------------------------------------------
@click.command()
@click.option('--verbose', is_flag=True, default=False, help='Print more details')
def main(verbose):
    bumble.logging.setup_basic_logging('WARNING')

    load_libusb()
    with usb1.USBContext() as context:
        bluetooth_device_count = 0
        devices = {}

        for device in context.getDeviceIterator(skip_on_error=True):
            device_class = device.getDeviceClass()
            device_subclass = device.getDeviceSubClass()
            device_protocol = device.getDeviceProtocol()

            device_id = (device.getVendorID(), device.getProductID())

            (device_class_string, device_subclass_string) = get_class_info(
                device_class, device_subclass, device_protocol
            )

            try:
                device_serial_number = device.getSerialNumber()
            except usb1.USBError:
                device_serial_number = None

            try:
                device_manufacturer = device.getManufacturer()
            except usb1.USBError:
                device_manufacturer = None

            try:
                device_product = device.getProduct()
            except usb1.USBError:
                device_product = None

            device_is_bluetooth_hci = is_bluetooth_hci(device)
            if device_is_bluetooth_hci:
                bluetooth_device_count += 1
                fg_color = 'black'
                bg_color = 'yellow'
            else:
                fg_color = 'yellow'
                bg_color = 'black'

            # Compute the different ways this can be referenced as a Bumble transport
            bumble_transport_names = []
            basic_transport_name = (
                f'usb:{device.getVendorID():04X}:{device.getProductID():04X}'
            )

            if device_is_bluetooth_hci:
                bumble_transport_names.append(f'usb:{bluetooth_device_count - 1}')

            if device_id not in devices:
                bumble_transport_names.append(basic_transport_name)
            else:
                bumble_transport_names.append(
                    f'{basic_transport_name}#{len(devices[device_id])}'
                )

            if device_serial_number is not None:
                if (
                    device_id not in devices
                    or device_serial_number not in devices[device_id]
                ):
                    bumble_transport_names.append(
                        f'{basic_transport_name}/{device_serial_number}'
                    )

            # Print the results
            print(
                color(
                    f'ID {device.getVendorID():04X}:{device.getProductID():04X}',
                    fg=fg_color,
                    bg=bg_color,
                )
            )
            if bumble_transport_names:
                print(
                    color('  Bumble Transport Names:', 'blue'),
                    ' or '.join(
                        color(x, 'cyan' if device_is_bluetooth_hci else 'red')
                        for x in bumble_transport_names
                    ),
                )
            print(
                color('  Bus/Device:            ', 'green'),
                f'{device.getBusNumber():03}/{device.getDeviceAddress():03}',
            )
            print(color('  Class:                 ', 'green'), device_class_string)
            print(color('  Subclass/Protocol:     ', 'green'), device_subclass_string)
            if device_serial_number is not None:
                print(color('  Serial:                ', 'green'), device_serial_number)
            if device_manufacturer is not None:
                print(color('  Manufacturer:          ', 'green'), device_manufacturer)
            if device_product is not None:
                print(color('  Product:               ', 'green'), device_product)

            if verbose:
                show_device_details(device)

            print()

            devices.setdefault(device_id, []).append(device_serial_number)


# -----------------------------------------------------------------------------
if __name__ == '__main__':
    main()  # pylint: disable=no-value-for-parameter