1
|
import logging
|
2
|
|
3
|
import usb.core
|
4
|
import usb.util
|
5
|
|
6
|
|
7
|
# list of devices from which the application
|
8
|
# could not retrieve a serial number
|
9
|
_invalid_devices = []
|
10
|
|
11
|
|
12
|
def read_connected_devices():
|
13
|
"""Reads and returns all USB devices that are 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 of a device, it
|
18
|
will store it into an in-RAM list to prevent "spam" logs. Once the application
|
19
|
manages 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
|
"""
|
23
|
logging.debug("reading all currently connected devices")
|
24
|
|
25
|
# Create an empty list of USB devices.
|
26
|
detected_devices = []
|
27
|
|
28
|
# Get a list of all buses.
|
29
|
busses = usb.busses()
|
30
|
|
31
|
for bus in busses:
|
32
|
# Get all devices connected to the current bus.
|
33
|
devices = bus.devices
|
34
|
for dev in devices:
|
35
|
# Create a record of the device.
|
36
|
device = {
|
37
|
"vendor_id": dev.idVendor,
|
38
|
"product_id": dev.idProduct
|
39
|
}
|
40
|
|
41
|
# Try to retrieve the serial number of the device.
|
42
|
serial_number = None
|
43
|
device_info = usb.core.find(idProduct=dev.idProduct)
|
44
|
try:
|
45
|
serial_number = usb.util.get_string(device_info, device_info.iSerialNumber)
|
46
|
except ValueError:
|
47
|
# If you fail, store the device into the in-RAM list (if it is not already there).
|
48
|
if device not in _invalid_devices:
|
49
|
logging.warning(f"Could not retrieve serial number from device {device}")
|
50
|
_invalid_devices.append(device)
|
51
|
|
52
|
if serial_number is not None:
|
53
|
# If you manage to read the serial number of a USB device
|
54
|
# that was previously stored into the list of "failures", remove it.
|
55
|
if device in _invalid_devices:
|
56
|
_invalid_devices.remove(device)
|
57
|
|
58
|
# Add the serial number into to USB device record.
|
59
|
device["serial_number"] = serial_number
|
60
|
|
61
|
# Append the record into the list of the connected USB devices.
|
62
|
detected_devices.append(device)
|
63
|
|
64
|
# Return the list of currently plugged USB devices.
|
65
|
return detected_devices
|