Revize 1526cb8b
Přidáno uživatelem Jakub Šilhavý před více než 2 roky(ů)
client/src/usb_detector/usb_reader.py | ||
---|---|---|
4 | 4 |
import usb.util |
5 | 5 |
|
6 | 6 |
|
7 |
# list of devices from which the application |
|
8 |
# could not retrieve a serial number |
|
7 | 9 |
_invalid_devices = [] |
8 | 10 |
|
9 | 11 |
|
10 | 12 |
def read_connected_devices(): |
13 |
"""Reads and returns all USB devices currently connected to the computer. |
|
14 |
|
|
15 |
It iterates over devices connected to individual buses and for each of |
|
16 |
them, it tries to retrieve its vendor id, product id, and serial number. |
|
17 |
If the application fails to retrieve the serial number from a device, it |
|
18 |
will be stored into an in-RAM list to prevent "spam" logs. Once the application |
|
19 |
successes to read the serial number, the device will be removed from the list. |
|
20 |
|
|
21 |
:return: list of all USB devices connected to the PC |
|
22 |
""" |
|
11 | 23 |
logging.debug("reading all currently connected devices") |
24 |
|
|
25 |
# Create an empty list of USB devices. |
|
12 | 26 |
detected_devices = [] |
13 | 27 |
|
28 |
# Get a list of all buses. |
|
14 | 29 |
busses = usb.busses() |
15 | 30 |
|
16 | 31 |
for bus in busses: |
32 |
# Get all devices connected to the current bus. |
|
17 | 33 |
devices = bus.devices |
18 | 34 |
for dev in devices: |
35 |
# Create a record of the device. |
|
19 | 36 |
device = { |
20 | 37 |
"vendor_id": dev.idVendor, |
21 | 38 |
"product_id": dev.idProduct |
22 | 39 |
} |
40 |
|
|
41 |
# Try to retrieve the serial number of the device. |
|
23 | 42 |
serial_number = None |
24 | 43 |
device_info = usb.core.find(idProduct=dev.idProduct) |
25 | 44 |
try: |
26 | 45 |
serial_number = usb.util.get_string(device_info, device_info.iSerialNumber) |
27 | 46 |
except ValueError: |
47 |
# If you fail, store the device into the in-RAM list (if it's |
|
48 |
# not already there). |
|
28 | 49 |
if device not in _invalid_devices: |
29 | 50 |
logging.warning(f"Could not retrieve serial number from device {device}") |
30 | 51 |
_invalid_devices.append(device) |
31 | 52 |
|
32 | 53 |
if serial_number is not None: |
54 |
# If you manage to read the serial number of a USB device |
|
55 |
# that was previously stored into the list of "failures", remove it. |
|
33 | 56 |
if device in _invalid_devices: |
34 | 57 |
_invalid_devices.remove(device) |
35 | 58 |
|
59 |
# Add the serial number into to USB device record. |
|
36 | 60 |
device["serial_number"] = serial_number |
61 |
|
|
62 |
# Append the record into the list of the connected USB devices. |
|
37 | 63 |
detected_devices.append(device) |
38 | 64 |
|
65 |
# Return the list of currently plugged USB devices. |
|
39 | 66 |
return detected_devices |
Také k dispozici: Unified diff
re #9422 Commented detector.py, event_listener.py, and usb_reader.py