-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathusbreset.py
executable file
·68 lines (58 loc) · 1.9 KB
/
usbreset.py
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
#!/usr/bin/python3
"""
Example code for resetting the USB ports
"""
import os
import fcntl
import subprocess
import re
# Equivalent of the _IO('U', 20) constant in the linux kernel.
USBDEVFS_RESET = ord('U') << (4*2) | 20
def get_buslist(filter=None):
"""
Gets the devfs paths by scraping the output of the lsusb command
The lsusb command outputs a list of USB devices attached to a computer
in the format:
Bus 002 Device 009: ID 16c0:0483 Van Ooijen Technische Informatica Teensyduino Serial
The devfs path to these devices is:
/dev/bus/usb/<busnum>/<devnum>
So for the above device, it would be:
/dev/bus/usb/002/009
This function generates that path.
"""
proc = subprocess.Popen(['lsusb'], stdout=subprocess.PIPE)
out = proc.communicate()[0]
if type(out) is bytes:
out = out.decode('cp866')
lines = out.split('\n')
ret = list()
for line in lines:
parts = line.split()
if len(parts) >= 4:
if filter is None or re.search(filter, line, flags=re.I):
#print(line, parts)
bus = parts[1]
dev = parts[3][:3]
ret.append('/dev/bus/usb/%s/%s' % (bus, dev))
return ret
def send_reset(dev_path):
"""
Sends the USBDEVFS_RESET IOCTL to a USB device.
dev_path - The devfs path to the USB device (under /dev/bus/usb/)
See get_teensy for example of how to obtain this.
"""
fd = os.open(dev_path, os.O_WRONLY)
try:
fcntl.ioctl(fd, USBDEVFS_RESET, 0)
finally:
os.close(fd)
if __name__ == '__main__':
import sys
if len(sys.argv) > 1:
arg = sys.argv[-1]
buslist = get_buslist(arg)
if buslist:
print('reset', buslist[0])
send_reset(buslist[0])
else:
print('Usage: %s <filter>' % sys.argv[0])