-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathUSB_FT232H.py
78 lines (70 loc) · 2.57 KB
/
USB_FT232H.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
68
69
70
71
72
73
74
75
76
77
78
def open_ft_usb_device(device_type, device_name, serial):
b_device_name = bytes(device_name, encoding="ASCII")
try:
import ftd2xx
except:
return None, 'Failed to import ftd2xx'
try:
usb = ftd2xx.openEx(serial)
except:
return None, 'Faled to open device'
if usb.description != b_device_name:
usb.close()
#print('Device did not match:', usb.description, b_device_name)
return None, 'Other type of USB device: '+str(usb.description)
else:
usb.setBitMode(0xff, 0x40)
#print(usb.getDeviceInfo())
#print(usb.getComPortNumber())
return usb, 'Successfully opened %s USB device: %s %s' % (device_type, device_name, serial)
class UsbFt232hSync245mode:
def __init__(self, device_type, device_name, serial):
usb, message = open_ft_usb_device(device_type, device_name, serial)
print(message)
self.good=False
if usb is not None:
self.good=True
self.device_type = device_type
self.device_name = device_name
self.serial = serial
self._usb = usb
self._recv_timeout = 250
self._send_timeout = 2000
self.set_recv_timeout(self._recv_timeout)
self.set_send_timeout(self._send_timeout)
self.set_latencyt(1) # ms
self._chunk = 65536
usb.setUSBParameters(self._chunk * 4, self._chunk * 4)
def close(self):
self._usb.close()
self._usb = None
def set_latencyt(self, latency):
self._usb.setLatencyTimer(latency)
def set_recv_timeout(self, timeout):
self._recv_timeout = timeout
self._usb.setTimeouts(self._recv_timeout, self._send_timeout)
def set_send_timeout(self, timeout):
self._send_timeout = timeout
self._usb.setTimeouts(self._recv_timeout, self._send_timeout)
def send(self, data):
txlen = 0
for si in range(0, len(data), self._chunk):
ei = si + self._chunk
ei = min(ei, len(data))
chunk = data[si:ei]
txlen_once = self._usb.write(chunk)
txlen += txlen_once
if txlen_once < len(chunk):
break
return txlen
def recv(self, recv_len):
data = b''
for si in range(0, recv_len, self._chunk):
ei = si + self._chunk
ei = min(ei, recv_len)
chunk_len = ei - si
chunk = self._usb.read(chunk_len)
data += chunk
if len(chunk) < chunk_len:
break
return data