-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathft232r.py
334 lines (276 loc) · 9.55 KB
/
ft232r.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# Copyright (C) 2011 by fpgaminer <[email protected]>
# fizzisist <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import d2xx
import struct
from jtag import JTAG
import time
from threading import RLock
DEFAULT_FREQUENCY = 3000000
class DeviceNotOpened(Exception): pass
class NoAvailableDevices(Exception): pass
class InvalidChain(Exception): pass
class WriteError(Exception): pass
class FT232R_PortList:
"""Information about which of the 8 GPIO pins to use."""
def __init__(self, tck0, tms0, tdi0, tdo0, tck1, tms1, tdi1, tdo1):
self.tck0 = tck0
self.tms0 = tms0
self.tdi0 = tdi0
self.tdo0 = tdo0
self.tck1 = tck1
self.tms1 = tms1
self.tdi1 = tdi1
self.tdo1 = tdo1
def output_mask(self):
return (1 << self.tck0) | (1 << self.tms0) | (1 << self.tdi0) | \
(1 << self.tck1) | (1 << self.tms1) | (1 << self.tdi1)
def format(self, tck, tms, tdi, chain=2):
"""Format the pin states as a single byte for sending to the FT232R
Chain is the JTAG chain: 0 or 1, or 2 for both
"""
if chain == 0:
return struct.pack('=c', chr(((tck&1) << self.tck0) |
((tms&1) << self.tms0) |
((tdi&1) << self.tdi0)))
if chain == 1:
return struct.pack('=c', chr(((tck&1) << self.tck1) |
((tms&1) << self.tms1) |
((tdi&1) << self.tdi1)))
if chain == 2:
return struct.pack('=c', chr(((tck&1) << self.tck0) |
((tms&1) << self.tms0) |
((tdi&1) << self.tdi0) |
((tck&1) << self.tck1) |
((tms&1) << self.tms1) |
((tdi&1) << self.tdi1)))
else:
raise InvalidChain()
def chain_portlist(self, chain=0):
"""Returns a JTAG_PortList object for the specified chain"""
if chain == 0:
return JTAG_PortList(self.tck0, self.tms0, self.tdi0, self.tdo0)
elif chain == 1:
return JTAG_PortList(self.tck1, self.tms1, self.tdi1, self.tdo1)
elif chain == 2:
return self
else:
raise InvalidChain()
class JTAG_PortList:
"""A smaller version of the FT232R_PortList class, specific to the JTAG chain"""
def __init__(self, tck, tms, tdi, tdo):
self.tck = tck
self.tms = tms
self.tdi = tdi
self.tdo = tdo
def format(self, tck, tms, tdi):
return struct.pack('=c', chr(((tck&1) << self.tck) |
((tms&1) << self.tms) |
((tdi&1) << self.tdi)))
class FT232R:
def __init__(self):
self.handle = None
self.debug = 0
self.synchronous = None
self.write_buffer = ""
self.portlist = None
self.devicenum = None
self.serial = ""
self.lock = RLock()
def __enter__(self):
return self
# Be sure to close the opened handle, if there is one.
# The device may become locked if we don't (requiring an unplug/plug cycle)
def __exit__(self, exc_type, exc_value, traceback):
self.close()
return False
def _log(self, msg, level=1):
if level <= self.debug:
print "FT232R:", msg
def open(self, devicenum, portlist):
"""Open an FT232R device with devicenum and initialize with the portlist"""
if self.handle is not None:
self.close()
if devicenum is None:
self._log("Opening first available device...")
devices = d2xx.listDevices()
available_device = False
for num, serial in enumerate(devices):
try:
h = d2xx.open(num)
h.close()
available_device = True
break
except:
pass
if available_device:
devicenum = num
if devicenum is not None:
self.handle = d2xx.open(devicenum)
if self.handle is not None:
self._log("Opened device %i" % devicenum)
self.devicenum = devicenum
self.portlist = portlist
self.serial = self.handle.getDeviceInfo()['serial']
self._setBaudRate(DEFAULT_FREQUENCY)
self._setSyncMode()
self._purgeBuffers()
return True
else:
return False
def close(self):
if self.handle is None:
return
with self.lock:
self._log("Closing device...")
try:
self.handle.close()
finally:
self.handle = None
self._log("Device closed.")
# Purges the FT232R's buffers.
def _purgeBuffers(self):
if self.handle is None:
raise DeviceNotOpened()
self.handle.purge(0)
def _setBaudRate(self, rate):
self._log("Setting baudrate to %i" % rate)
# Documentation says that we should set a baudrate 16 times lower than
# the desired transfer speed (for bit-banging). However I found this to
# not be the case. 3Mbaud is the maximum speed of the FT232RL
self.handle.setBaudRate(rate)
#self.handle.setDivisor(0) # Another way to set the maximum speed.
def _setSyncMode(self):
"""Put the FT232R into Synchronous mode."""
if self.handle is None:
raise DeviceNotOpened()
self._log("Device entering Synchronous mode.", 2)
self.handle.setBitMode(self.portlist.output_mask(), 0)
self.handle.setBitMode(self.portlist.output_mask(), 4)
self.synchronous = True
def _setAsyncMode(self):
"""Put the FT232R into Asynchronous mode."""
if self.handle is None:
raise DeviceNotOpened()
self._log("Device entering Asynchronous mode.", 2)
self.handle.setBitMode(self.portlist.output_mask(), 0)
self.handle.setBitMode(self.portlist.output_mask(), 1)
self.synchronous = False
def _setCBUSBits(self, sc, cs):
# CBUS pins:
# SIO_0 = CBUS0 = input
# SIO_1 = CBUS1 = input
# CS = CBUS2 = output
# SC = CBUS3 = output
SIO_0 = 0
SIO_1 = 1
CS = 2
SC = 3
read_mask = ( (1 << SC) | (1 << CS) | (0 << SIO_1) | (0 << SIO_0) ) << 4
CBUS_mode = 0x20
# set up I/O and start conversion:
pin_state = (sc << SC) | (cs << CS)
self.handle.setBitMode(read_mask | pin_state, CBUS_mode)
def _getCBUSBits(self):
SIO_0 = 0
SIO_1 = 1
data = self.handle.getBitMode()
return (((data >> SIO_0) & 1), ((data >> SIO_1) & 1))
def flush(self):
"""Write all data in the write buffer and purge the FT232R buffers"""
self._setAsyncMode()
while len(self.write_buffer) > 0:
self.handle.write(self.write_buffer[:4096])
self.write_buffer = self.write_buffer[4096:]
self._setSyncMode()
self._purgeBuffers()
def write(self, data):
return self.handle.write(data)
def getStatus(self):
return self.handle.getStatus()
def getQueueStatus(self):
return self.handle.getQueueStatus()
def read_data(self, num):
"""Read num bytes from the FT232R and return an array of data."""
self._log("Reading %d bytes." % num, 3)
if num == 0:
self.flush()
return []
# Repeat the last byte so we can read the last bit of TDO.
write_buffer = self.write_buffer[-(num*3):]
self.write_buffer = self.write_buffer[:-(num*3)]
# Write all data that we don't care about.
if len(self.write_buffer) > 0:
self._log("Flushing out " + str(len(self.write_buffer)), 3)
self.flush()
self._purgeBuffers()
data = []
while len(write_buffer) > 0:
bytes_to_write = min(len(write_buffer), 3072)
self._log("Writing %d/%d bytes" % (bytes_to_write, len(write_buffer)), 3)
wrote = self.handle.write(write_buffer[:bytes_to_write])
self._log("Wrote %d bytes" % wrote, 3)
if wrote != bytes_to_write:
raise WriteError()
write_buffer = write_buffer[wrote:]
#self._log("Status: " + str(self.handle.getStatus()))
#self._log("QueueStatus: " + str(self.handle.getQueueStatus()))
start_time = time.time()
while self.handle.getQueueStatus() < wrote:
if time.time() - start_time > 5:
self._log("Timeout while reading data!")
return data
#time.sleep(0.1)
#self._log("QueueStatus: " + str(self.handle.getQueueStatus()))
data.extend(self.handle.read(wrote))
self._log("Read %d bytes." % len(data), 3)
return data
def read_temps(self):
self._log("Reading temp sensors.")
# clock SC with CS high:
self._setCBUSBits(0, 1)
self._setCBUSBits(1, 1)
self._setCBUSBits(0, 1)
self._setCBUSBits(1, 1)
# drop CS to start conversion:
self._setCBUSBits(0, 0)
code0 = 0
code1 = 0
for i in range(16):
self._setCBUSBits(1, 0)
(sio_0, sio_1) = self._getCBUSBits()
code0 |= sio_0 << (15 - i)
code1 |= sio_1 << (15 - i)
self._setCBUSBits(0, 0)
# assert CS and clock SC:
self._setCBUSBits(0, 1)
self._setCBUSBits(1, 1)
self._setCBUSBits(0, 1)
if (code0 >> 15) & 1 == 1: code0 -= (1 << 16)
if (code1 >> 15) & 1 == 1: code1 -= (1 << 16)
if code0 == 0xFFFF or code0 == 0:
temp0 = None
else:
temp0 = (code0 >> 2) * 0.03125
if code1 == 0xFFFF or code1 == 0:
temp1 = None
else:
temp1 = (code1 >> 2) * 0.03125
return (temp0, temp1)