128
|
1 import sys
|
129
|
2 import usb
|
128
|
3
|
|
4 # Global device list to which devices are registered.
|
129
|
5 devices = {}
|
128
|
6
|
|
7 def registerDevice(chipId):
|
|
8 """ Decorator to register a device """
|
|
9 def wrapper(dev):
|
129
|
10 devices[chipId] = dev
|
128
|
11 return dev
|
|
12 return wrapper
|
|
13
|
|
14 # Global interface dictionary.
|
|
15 interfaces = {}
|
|
16
|
|
17 def registerInterface(vid_pid):
|
|
18 def wrapper(iface):
|
|
19 interfaces[vid_pid] = iface
|
|
20 return iface
|
|
21 return wrapper
|
|
22
|
129
|
23 def createInterfaces():
|
|
24 """ Create a list of detected interfaces """
|
|
25 ctx = usb.UsbContext()
|
|
26
|
|
27 # Retrieve all usb devices:
|
|
28 devs = ctx.DeviceList
|
|
29 keys = interfaces.keys()
|
|
30
|
|
31 # Filter function to filter only registered interfaces:
|
|
32 def filt(usbiface):
|
|
33 return (usbiface.VendorId, usbiface.ProductId) in keys
|
|
34 def buildInterface(usbiface):
|
|
35 key = (usbiface.VendorId, usbiface.ProductId)
|
|
36 iface = interfaces[key]
|
|
37 return iface(usbiface)
|
|
38 return [buildInterface(uif) for uif in filter(filt, devs)]
|
|
39
|
128
|
40 class Device:
|
|
41 """
|
|
42 Base class for a device possibly connected via an interface.
|
|
43 """
|
129
|
44 def __init__(self, iface):
|
|
45 # Store the interface through which this device is connected:
|
|
46 assert isinstance(iface, Interface)
|
|
47 self.iface = iface
|
128
|
48
|
|
49 class Interface:
|
|
50 """
|
|
51 Generic interface class. Connected via Usb to a JTAG interface.
|
|
52 Possibly is connected with a certain chip.
|
|
53 """
|
129
|
54 def createDevice(self):
|
128
|
55 """ Try to get the device connected to this interface """
|
129
|
56 if self.ChipId in devices:
|
|
57 return devices[self.ChipId](self)
|
128
|
58 raise STLinkException('No device found!')
|
|
59
|
|
60 class STLinkException(Exception):
|
|
61 """ Exception used for interfaces and devices """
|
|
62 pass
|
|
63
|