-
Notifications
You must be signed in to change notification settings - Fork 7
/
ftI2cGui.py
449 lines (383 loc) · 17.7 KB
/
ftI2cGui.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
from ft_function import FT260_STATUS, FT260_I2C_FLAG, FT260_I2C_STATUS
import ft
import time
import struct
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.scrolledtext as tkst
FT260_Vid = 0x0403
FT260_Pid = 0x6030
config = None
class _ConfigFrame(tk.Frame):
@property
def clock(self):
return self.entry_clock.get()
@clock.setter
def clock(self, new_value):
self.entry_clock.delete(0, tk.END)
self.entry_clock.insert(0, new_value)
@property
def slave_address(self):
return self.entry_address.get()
@slave_address.setter
def slave_address(self, new_value):
self.entry_address.delete(0, tk.END)
self.entry_address.insert(0, new_value)
def open(self):
ft.open_ftlib()
if self.i2c_handle is not None:
raise Exception("Device already opened. Action to open it twice should be disabled.")
if not ft.find_device_in_paths(FT260_Vid, FT260_Pid):
self.entry_scroll_message.delete("1.0", tk.END)
self.entry_scroll_message.insert("1.0", """No FT260 Device found. Was looking USB devices by VID/PID combination and didn't find any.
Did you forget to connect FT260 chip to USB?
Did you install the driver?
Do you see FT260 in device list?"""
)
return
self.i2c_handle = ft.openFtAsI2c(FT260_Vid, FT260_Pid, int(self.clock))
if self.i2c_handle is None:
self.entry_scroll_message.delete("1.0", tk.END)
self.entry_scroll_message.insert("1.0", "Open I2C error. Was opening FT260 in I2C mode and failed.")
return
self.button_open.config(state="disable")
self.entry_clock.config(state="disable")
self.button_close.config(state="normal")
self.entry_scroll_message.delete("1.0", tk.END)
def close(self):
if self.i2c_handle is not None:
ft.close_device(self.i2c_handle)
self.i2c_handle = None
self.button_open.config(state="normal")
self.entry_clock.config(state="normal")
self.button_close.config(state="disable")
else:
raise Exception("Device is not opened. Action to close it twice should be disabled.")
def __del__(self):
if self.i2c_handle is not None:
ft.close_device(self.i2c_handle)
def __init__(self, parent):
self.parent = parent
self.i2c_handle = None
super().__init__(self.parent)
self.config(pady=5)
self.grid_columnconfigure(4, weight=1)
label_clock = tk.Label(self, text="Clock rate [kbps]:")
label_address = tk.Label(self, text="I2C slave device address [hex]:")
self.entry_clock = tk.Entry(self, width=6)
self.entry_address = tk.Entry(self, width=6)
self.button_open = tk.Button(self, text="Open device", command=self.open)
self.button_close = tk.Button(self, text="Close device", command=self.close, state="disabled")
self.entry_scroll_message = tkst.ScrolledText(self, height="3", width="20")
label_msb_warning = tk.Label(self, text="Multiple bytes are send and read as MSByte first, LSByte last.")
label_clock.grid(row=0, column=0, padx=(3, 0))
self.entry_clock.grid(row=0, column=1)
label_address.grid(row=1, column=0, padx=(3, 0))
self.entry_address.grid(row=1, column=1)
self.button_open.grid(row=0, column=2, padx=(3, 0))
self.button_close.grid(row=0, column=3)
self.entry_scroll_message.grid(row=0, column=4, rowspan=3, sticky="nsew", padx=5)
label_msb_warning.grid(row=2, column=0, padx=(3, 0), columnspan=4)
class _DeviceScannerFrame(tk.Frame):
global config
def scan_button(self):
if config.i2c_handle is None:
return
self.entry_addresses.delete(0, tk.END)
for address in range(1, 127):
(ft_status, data_real_read_len, readData, status) = ft.ftI2cRead(config.i2c_handle,
address,
FT260_I2C_FLAG.FT260_I2C_START_AND_STOP,
1)
if not (status & FT260_I2C_STATUS.FT260_SLAVE_NACK):
self.entry_addresses.insert(tk.END, hex(address) + " ")
def __init__(self, parent):
self.parent = parent
super().__init__(self.parent)
self.config(pady=5)
self.grid_columnconfigure(2, weight=1)
button_scan = tk.Button(self, text="Scan I2C bus", command=self.scan_button)
label_scan_result = tk.Label(self, text="Found addresses:")
self.entry_addresses = tk.Entry(self, width=30)
button_scan.grid(row=0, column=0)
label_scan_result.grid(row=0, column=1, padx=(3, 0))
self.entry_addresses.grid(row=0, column=2, sticky="ew")
class _RegFrame(tk.Frame):
global config
def read_button(self):
if config.i2c_handle is None:
return
packstr = ['>', 'B' if self.register_address_size == 1 else 'H']
unpackstr = ['>', 'B']
if self.register_size == 2:
unpackstr[1] = 'H'
elif self.register_size == 4:
unpackstr[1] = 'I'
# Interpret register address as hexadecimal value
reg_addr = int(self.register_address, 16)
# Interpret device address as hexadecimal value
dev_addr = int(config.slave_address, 16)
ft.ftI2cWrite(config.i2c_handle,
dev_addr,
FT260_I2C_FLAG.FT260_I2C_START,
struct.pack("".join(packstr), reg_addr))
# Register address is send. Can now retrieve register data
(ft_status, data_real_read_len, readData, status) = ft.ftI2cRead(config.i2c_handle,
dev_addr,
FT260_I2C_FLAG.FT260_I2C_START_AND_STOP,
self.register_size)
if data_real_read_len != len(readData):
print("Read {} bytes from ft260 lib, but {} bytes are in buffer".format(data_real_read_len, len(readData)))
elif not ft_status == FT260_STATUS.FT260_OK.value:
print("Read error : %s\r\n" % ft_status)
if not len(readData) == 0:
self.register_value = "%#x" % struct.unpack("".join(unpackstr), readData)
def write_button(self):
if config.i2c_handle is None:
return
packstr = ['>', 'B', 'B']
if self.register_address_size == 2:
packstr[1] = 'H'
if self.register_size == 2:
packstr[2] = 'H'
elif self.register_size == 4:
packstr[2] = 'I'
# Interpret register address as hexadecimal value
reg_addr = int(self.register_address, 16)
# Interpret device address as hexadecimal value
dev_addr = int(config.slave_address, 16)
# Interpret value to write as hexadecimal value
try:
reg_value = int(self.register_value, 16)
# Single hex value may not be valid for any reason. Just drop execution then.
except ValueError:
return
ft.ftI2cWrite(config.i2c_handle, dev_addr, FT260_I2C_FLAG.FT260_I2C_START_AND_STOP,
struct.pack("".join(packstr), reg_addr, reg_value))
@property
def register_address(self):
return self.entry_address.get()
@register_address.setter
def register_address(self, new_value):
self.entry_address.delete(0, tk.END)
self.entry_address.insert(0, new_value)
@property
def register_value(self):
return self.entry_value.get()
@register_value.setter
def register_value(self, new_value):
self.entry_value.delete(0, tk.END)
self.entry_value.insert(0, new_value)
@property
def register_address_size(self):
size = self.combo_reg_bits.get()
if size == "8 bits":
return 1
elif size == "16 bits":
return 2
else:
raise Exception("Unknown option {} in register_address_size combobox.".format(bytes))
@property
def register_size(self):
size = self.combo_value_bits.get()
if size == "8 bits":
return 1
elif size == "16 bits":
return 2
elif size == "32 bits":
return 4
else:
raise Exception("Unknown option {} in register_size combobox.".format(bytes))
def __init__(self, parent):
self.parent = parent
super().__init__(self.parent)
self.config(pady=5)
label_reg_bits = tk.Label(self, text="Register address size:")
self.combo_reg_bits = ttk.Combobox(self, values=["8 bits", "16 bits"], width=6)
self.combo_reg_bits.current(0)
label_address = tk.Label(self, text="Register address:")
self.entry_address = tk.Entry(self, width=6)
label_value_bits = tk.Label(self, text="Register value size:")
self.combo_value_bits = ttk.Combobox(self, values=["8 bits", "16 bits", "32 bits"], width=6)
self.combo_value_bits.current(0)
label_value = tk.Label(self, text="Register value:")
self.entry_value = tk.Entry(self, width=10)
button_write = tk.Button(self, text="Write", command=self.write_button)
button_read = tk.Button(self, text="Read", command=self.read_button)
label_reg_bits.grid(row=0, column=0, padx=(3, 0))
self.combo_reg_bits.grid(row=0, column=1)
label_address.grid(row=0, column=2, padx=(3, 0))
self.entry_address.grid(row=0, column=3)
label_value_bits.grid(row=0, column=4, padx=(3, 0))
self.combo_value_bits.grid(row=0, column=5)
label_value.grid(row=0, column=6, padx=(3, 0))
self.entry_value.grid(row=0, column=7)
button_write.grid(row=0, column=8)
button_read.grid(row=0, column=9)
class _DataFrame(tk.Frame):
global config
@property
def data_size(self):
return self.entry_data_size.get()
@data_size.setter
def data_size(self, new_value):
self.entry_data_size.delete(0, tk.END)
self.entry_data_size.insert(0, new_value)
@property
def data(self):
return self.entry_data.get()
@data.setter
def data(self, new_value):
self.entry_data.delete(0, tk.END)
self.entry_data.insert(0, new_value)
@property
def data_word(self):
size = self.combo_word_size.get()
if size == "8 bits":
return 1
elif size == "16 bits":
return 2
elif size == "32 bits":
return 4
else:
raise Exception("Unknown option {} in data_word combobox.".format(bytes))
def write_button(self):
if config.i2c_handle is None:
return
data_to_write = self.data.split(' ')
words = []
packstr = '>'
for hex_word in data_to_write:
if hex_word != "":
words.append(int(hex_word, 16))
packstr += self.word_symbol[self.data_word]
(ft_status, data_real_write_len, writeData, status) = ft.ftI2cWrite(config.i2c_handle,
int(config.slave_address, 16),
FT260_I2C_FLAG.FT260_I2C_START_AND_STOP,
struct.pack("".join(packstr), *words)
)
unpackstr = ">" + self.word_symbol[self.data_word] * int(len(writeData) / self.data_word)
update_str = ""
for index, value in enumerate(struct.unpack(unpackstr, writeData)):
if index >= data_real_write_len:
break
update_str = update_str + hex(value) + " "
self.data = update_str
def read_button(self):
if config.i2c_handle is None:
return
(ft_status, data_real_read_len, readData, status) = ft.ftI2cRead(config.i2c_handle,
int(config.slave_address, 16),
FT260_I2C_FLAG.FT260_I2C_START_AND_STOP,
int(self.data_size) * self.data_word)
# Error checking
if data_real_read_len != len(readData):
print("Read {} bytes from ft260 lib, but {} bytes are in buffer".format(data_real_read_len,
len(readData)))
elif not ft_status == FT260_STATUS.FT260_OK.value:
print("Read error : %s\r\n" % ft_status)
unpackstr = ">" + self.word_symbol[self.data_word] * int(len(readData) / self.data_word)
update_str = ""
for i in struct.unpack(unpackstr, readData):
update_str = update_str + hex(i) + " "
self.data = update_str
def __init__(self, parent):
self.parent = parent
super().__init__(self.parent)
self.config(pady=5)
self.grid_columnconfigure(5, weight=1)
label_data_size = tk.Label(self, text="Data length:")
self.entry_data_size = tk.Entry(self, width=6)
label_word_size = tk.Label(self, text="Data word size:")
self.combo_word_size = ttk.Combobox(self, values=["8 bits", "16 bits", "32 bits"], width=6)
self.combo_word_size.current(0)
label_data = tk.Label(self, text="Data [hex]:")
self.entry_data = tk.Entry(self, width=30)
button_write = tk.Button(self, text="Write", command=self.write_button)
button_read = tk.Button(self, text="Read", command=self.read_button)
label_data_size.grid(row=0, column=0, padx=(3, 0))
self.entry_data_size.grid(row=0, column=1)
label_word_size.grid(row=0, column=2, padx=(3, 0))
self.combo_word_size.grid(row=0, column=3)
label_data.grid(row=0, column=4, padx=(3, 0))
self.entry_data.grid(row=0, column=5, sticky="we")
button_write.grid(row=0, column=6)
button_read.grid(row=0, column=7)
self.word_symbol = {1: "B", 2: "H", 4: "I"}
class _CommLog(tk.Frame):
"""
Communication log for USB-I2C messages
"""
def __init__(self, parent):
"""
Constructor
"""
self.parent = parent
super().__init__(self.parent)
# Inside frame grid config
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
# Set the treeview
self.tree = ttk.Treeview(self, columns=('Timestamp', 'Direction', 'Address', 'Message', 'Mode', 'Status'))
self.tree.heading('#0', text='#')
self.tree.heading('#1', text='Timestamp')
self.tree.heading('#2', text='Direction')
self.tree.heading('#3', text='Address')
self.tree.heading('#4', text='Message')
self.tree.heading('#5', text='Mode')
self.tree.heading('#6', text='Status')
self.tree.column('#0', minwidth=46, width=46, stretch=tk.NO)
self.tree.column('#1', minwidth=130, width=130, stretch=tk.NO)
self.tree.column('#2', minwidth=70, width=70, stretch=tk.NO)
self.tree.column('#3', minwidth=70, width=70, stretch=tk.NO)
self.tree.column('#4', minwidth=130, width=130, stretch=tk.YES)
self.tree.column('#5', minwidth=90, width=90, stretch=tk.NO)
self.tree.column('#6', minwidth=50, width=50, stretch=tk.NO)
# Scrollbar
self.vsb = ttk.Scrollbar(self, orient="vertical", command=self.tree.yview)
self.tree.configure(yscrollcommand=self.vsb.set)
# Layout
self.tree.grid(row=0, column=0, sticky='nsew')
self.vsb.grid(row=0, column=1, sticky='ns')
# Initialize the counter
self.message_number = 0
def add_new_log_entry(self, itemlist):
"""
Callback to add data to log window.
:param itemlist: list with several items in the order of the tree columns
:return: None
"""
v = list()
v.append(time.strftime("%Y-%m-%d %H:%M:%S"))
v.extend(itemlist)
item = self.tree.insert('', 'end', text=str(self.message_number), values=v)
self.message_number += 1
self.tree.see(item)
def main():
global config
parent = tk.Tk()
parent.title("FT260 I2C")
config = _ConfigFrame(parent)
config.clock = "100"
config.slave_address = "0x68"
config.pack(fill="x", expand=False)
separator = ttk.Separator(parent, orient=tk.HORIZONTAL)
separator.pack(fill="x")
scanner = _DeviceScannerFrame(parent)
scanner.pack(fill="x")
separator = ttk.Separator(parent, orient=tk.HORIZONTAL)
separator.pack(fill="x")
reg = _RegFrame(parent)
reg.pack(fill="x")
reg.register_address = "0x00"
separator = ttk.Separator(parent, orient=tk.HORIZONTAL)
separator.pack(fill="x")
data = _DataFrame(parent)
data.data_size = 1
data.pack(fill="x")
comm_log = _CommLog(parent)
comm_log.pack(fill="both", expand=True)
ft._callback = comm_log.add_new_log_entry
parent.mainloop()
if __name__ == "__main__":
main()