1
|
|
|
from abc import abstractmethod |
2
|
|
|
from threading import Lock |
3
|
|
|
|
4
|
|
|
import usb |
5
|
|
|
|
6
|
|
|
|
7
|
|
|
class Driver: |
8
|
|
|
def __init__(self): |
9
|
|
|
self._lock = Lock() |
10
|
|
|
|
11
|
|
|
@abstractmethod |
12
|
|
|
def _isOpen(self): |
13
|
|
|
pass |
14
|
|
|
|
15
|
|
|
@abstractmethod |
16
|
|
|
def _open(self): |
17
|
|
|
pass |
18
|
|
|
|
19
|
|
|
@abstractmethod |
20
|
|
|
def _close(self): |
21
|
|
|
pass |
22
|
|
|
|
23
|
|
|
@abstractmethod |
24
|
|
|
def _read(self, count): |
25
|
|
|
pass |
26
|
|
|
|
27
|
|
|
@abstractmethod |
28
|
|
|
def _write(self, data): |
29
|
|
|
pass |
30
|
|
|
|
31
|
|
|
|
32
|
|
|
class SerialDriver(Driver): |
33
|
|
|
def __init__(self, device, baudRate=115200): |
34
|
|
|
super().__init__() |
35
|
|
|
self.device = device |
36
|
|
|
self.baudRate = baudRate |
37
|
|
|
|
38
|
|
|
def _close(self): |
39
|
|
|
pass |
40
|
|
|
|
41
|
|
|
def _open(self): |
42
|
|
|
pass |
43
|
|
|
|
44
|
|
|
def _write(self, data): |
45
|
|
|
pass |
46
|
|
|
|
47
|
|
|
def _isOpen(self): |
48
|
|
|
pass |
49
|
|
|
|
50
|
|
|
def _read(self, count): |
51
|
|
|
pass |
52
|
|
|
|
53
|
|
|
|
54
|
|
|
class USB2Driver(Driver): |
55
|
|
|
def __init__(self, idVendor, idProduct): |
56
|
|
|
Driver.__init__(self) |
57
|
|
|
self._idVendor = idVendor |
58
|
|
|
self._idProduct = idProduct |
59
|
|
|
self._dev = None |
60
|
|
|
self._epOut = None |
61
|
|
|
self._epIn = None |
62
|
|
|
self._interfaceNumber = None |
63
|
|
|
|
64
|
|
|
def _open(self): |
65
|
|
|
self._dev = usb.core.find(idVendor=self._idVendor, idProduct=self._idProduct) |
66
|
|
|
if self._dev is None: |
67
|
|
|
pass # TODO: Need exception here |
68
|
|
|
|
69
|
|
|
# take care of bugs with the kernel driver |
70
|
|
|
if self._dev.is_kernel_driver_active(0): |
71
|
|
|
try: |
72
|
|
|
self._dev.detach_kernel_driver(0) |
73
|
|
|
except usb.USBError as e: |
74
|
|
|
pass # TODO: Exception here couldn't detach kernel driver |
75
|
|
|
|
76
|
|
|
self._dev.set_configuration() |
77
|
|
|
cfg = self._dev.get_active_configuration() |
78
|
|
|
self._interfaceNumber = cfg[(0, 0)].bInterfaceNumber |
79
|
|
|
interface = usb.util.find_descriptor(cfg, bInterfaceNumber=self._interfaceNumber, |
80
|
|
|
bAlternateSetting=usb.control.get_interface(self._dev, |
81
|
|
|
self._interfaceNumber)) |
82
|
|
|
usb.util.claim_interface(self._dev, self._interfaceNumber) |
83
|
|
|
|
84
|
|
|
self._epOut = usb.util.find_descriptor(interface, custom_match=lambda e: usb.util.endpoint_direction( |
85
|
|
|
e.bEndpointAddress) == usb.ENDPOINT_OUT) |
86
|
|
|
assert self._epOut is not None # TODO: change to exception |
87
|
|
|
|
88
|
|
|
self._ep_in = usb.util.find_descriptor(interface, custom_match=lambda e: usb.util.endpoint_direction( |
89
|
|
|
e.bEndpointAddress) == usb.ENDPOINT_IN) |
90
|
|
|
assert self._ep_in is not None # TODO: change to exception |
91
|
|
|
|