forked from tinyfpga/TinyFPGA-Bootloader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__main__.py
485 lines (398 loc) · 15 KB
/
__main__.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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
#!/usr/bin/env python
from __future__ import print_function
import sys
import argparse
import json
import time
from six.moves.urllib.request import urlopen
from six.moves import input
import tinyprog
from tinyprog import TinyProg, get_ports, PortError
# adapted from http://code.activestate.com/recipes/577058/
def query_user(question, default="no"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write(
"Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
def strict_query_user(question):
valid = {"yes": True}
prompt = " [yes/NO] > "
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
return valid.get(choice, False)
def get_port_by_uuid(device, uuid):
ports = get_ports(device) + get_ports("1209:2100")
for port in ports:
try:
with port:
p = TinyProg(port)
if p.meta.uuid().startswith(uuid):
return port
except Exception:
pass
return None
def check_for_new_bootloader():
return []
def check_for_wrong_tinyfpga_bx_vidpid():
"""
Some of the TinyFPGA BX boards have the wrong USB VID:PID. This function
looks for such boards.
"""
boards_needing_update = []
ports = get_ports("1209:2100")
for port in ports:
with port:
p = TinyProg(port)
m = p.meta.root
if m[u"boardmeta"][u"name"] == u"TinyFPGA BX":
boards_needing_update.append(port)
return boards_needing_update
def check_if_overwrite_bootloader(addr, length, userdata_range):
ustart = userdata_range[0]
uend = userdata_range[1]
if addr < ustart or addr + length >= uend:
print("""\
!!! WARNING !!!
The address given may overwrite the USB bootloader. Without the
USB bootloader the board will no longer be able to be programmed
over the USB interface. Without the USB bootloader, the board can
only be programmed via the SPI flash interface on the bottom of
the board
""")
retval = strict_query_user(
" Are you sure you want to continue?"
"Type in 'yes' to overwrite bootloader.")
print("")
return retval
return True
def perform_bootloader_update(port):
uuid = None
with port:
p = TinyProg(port)
m = p.meta.root
uuid = m[u"boardmeta"][u"uuid"]
# download bootloader update information
bootloader_update_info = json.loads(
urlopen(m[u"bootmeta"][u"update"] + "/bootloader.json").read())
# ask permission to update the board
print("")
print(" The following update:")
print("")
print(" New Version: %s" % bootloader_update_info[u"version"])
print(" Notes: %s" % bootloader_update_info[u"notes"])
print("")
print(" is available for this board:")
print_board(port, m)
print("")
if query_user(" Would you like to perform the update?"):
####################
# STAGE ONE
####################
print(" Fetching stage one...")
bitstream = urlopen(
bootloader_update_info[u"stage_one_url"]).read()
print(" Programming stage one...")
userimage_addr = p.meta.userimage_addr_range()[0]
if p.program_bitstream(userimage_addr, bitstream):
p.boot()
print(" ...Success!")
else:
print(" ...Failure, try again!")
return False
else:
print(" Update cancelled by user.")
return False
sys.stdout.write(" Waiting for stage one to reconnect...")
sys.stdout.flush()
new_port = None
for x in range(20):
time.sleep(1)
sys.stdout.write(".")
sys.stdout.flush()
new_port = get_port_by_uuid("1d50:6130", uuid)
if new_port is not None:
print("connected!")
break
with new_port:
p = TinyProg(new_port)
####################
# STAGE TWO
####################
print(" Fetching stage two...")
bitstream = urlopen(bootloader_update_info[u"stage_two_url"]).read()
print(" Programming stage two...")
if p.program_bitstream(0, bitstream):
p.boot()
print(" ...Success!\n")
return True
else:
print(" ...Failure, try again!")
return False
def print_board(port, m):
if isinstance(m, dict) and u"boardmeta" in m:
print("")
print(
" %s: %s %s" %
(port, m[u"boardmeta"][u"name"], m[u"boardmeta"][u"hver"]))
print(" UUID: %s" % m[u"boardmeta"][u"uuid"])
print(" FPGA: %s" % m[u"boardmeta"][u"fpga"])
else:
print("")
print(" %s: No metadata" % (port))
def main():
def parse_int(str_value):
str_value = str_value.strip().lower()
if str_value.startswith("0x"):
return int(str_value[2:], 16)
else:
return int(str_value)
parser = argparse.ArgumentParser()
parser.add_argument(
"--version",
action="store_true",
help="Print the tinyprog version.")
parser.add_argument(
"-l",
"--list",
action="store_true",
help="list connected and active FPGA boards")
parser.add_argument(
"-p",
"--program",
type=str,
help="program FPGA board with the given user bitstream")
parser.add_argument(
"-u",
"--program-userdata",
type=str,
help="program FPGA board with the given user data")
parser.add_argument(
"--program-image",
type=str,
help="program FPGA board with a combined user bitstream and data")
parser.add_argument(
"-b",
"--boot",
action="store_true",
help="command the FPGA board to exit the "
"bootloader and load the user configuration")
parser.add_argument("-c", "--com", type=str, help="serial port name")
parser.add_argument("-i", "--id", type=str, help="FPGA board ID")
parser.add_argument(
"-d",
"--device",
type=str,
default="1d50:6130",
help="device id (vendor:product); default is (1d50:6130)")
parser.add_argument(
"-a",
"--addr",
type=str,
help="force the address to write the bitstream to")
parser.add_argument(
"-m",
"--meta",
action="store_true",
help="dump out the metadata for all connected boards in JSON")
parser.add_argument(
"--update-bootloader",
action="store_true",
help="check for new bootloader and update eligible connected boards")
parser.add_argument(
"--libusb",
action="store_true",
help="""\
try using libusb to connect to boards without a serial driver attached"""
)
parser.add_argument(
"--pyserial",
action="store_true",
help="use pyserial to connect to boards")
args = parser.parse_args()
if args.version:
print("tinyprog %s (%s)" % (
tinyprog.__version__, tinyprog.__full_version__))
sys.exit(0)
device = args.device.lower().replace(':', '')
if len(device) != 8 or not all(c in '0123456789abcdef' for c in device):
print(" Invalid device id, use format vendor:product")
sys.exit(1)
device = '{}:{}'.format(device[:4], device[4:])
tinyprog.use_libusb = args.libusb
tinyprog.use_pyserial = args.pyserial
try:
active_boards = get_ports(device) + get_ports("1209:2100")
if args.meta:
meta = []
for port in active_boards:
with port:
p = TinyProg(port)
m = p.meta.root
m["port"] = str(port)
meta.append(m)
print(json.dumps(meta, indent=2))
sys.exit(0)
print("")
print(" TinyProg CLI")
print(" ------------")
print(" Using device id {}".format(device))
# find port to use
active_port = None
if args.com is not None:
active_port = tinyprog.SerialPort(args.com)
elif args.id is not None:
active_port = get_port_by_uuid(device, args.id)
elif not active_boards:
print("""\
No port was specified and no active bootloaders found.
Activate bootloader by pressing the reset button.
""")
sys.exit(1)
elif len(active_boards) == 1:
print("""\
Only one board with active bootloader, using it.
""")
active_port = active_boards[0]
else:
print("""\
Please choose a board with the -c or -i option. Using first board in list.
""")
active_port = active_boards[0]
# list boards
if args.list or active_port is None:
print(" Boards with active bootloaders:")
for port in active_boards:
with port:
p = TinyProg(port)
m = p.meta.root
print_board(port, m)
if len(active_boards) == 0:
print("""\
No active bootloaders found. Check USB connections
and press reset button to activate bootloader.""")
if args.update_bootloader:
boards_needing_update = (
check_for_wrong_tinyfpga_bx_vidpid()
+ check_for_new_bootloader())
if len(boards_needing_update) == 0:
print("""\
All connected and active boards are up to date!""")
else:
for port in boards_needing_update:
perform_bootloader_update(port)
# program the flash memory
if (args.program is not None) or (
args.program_userdata is not None) or (
args.program_image is not None):
boot_fpga = False
def progress(info):
if isinstance(info, str):
print(" " + str(info))
with active_port:
fpga = TinyProg(active_port, progress)
if args.program is not None:
print(" Programming %s with %s" % (
active_port, args.program))
bitstream = fpga.slurp(args.program)
if args.addr is not None:
addr = parse_int(args.addr)
else:
addr = fpga.meta.userimage_addr_range()[0]
if addr < 0:
print(" Negative write addr: {}".format(addr))
sys.exit(1)
if not fpga.is_bootloader_active():
print(" Bootloader not active")
sys.exit(1)
if check_if_overwrite_bootloader(
addr, len(bitstream),
fpga.meta.userimage_addr_range()):
boot_fpga = True
print(" Programming at addr {:06x}".format(addr))
if not fpga.program_bitstream(addr, bitstream):
sys.exit(1)
# program user flash area
if args.program_userdata is not None:
print(" Programming %s with %s" % (
active_port, args.program_userdata))
bitstream = fpga.slurp(args.program_userdata)
if args.addr is not None:
addr = parse_int(args.addr)
else:
addr = fpga.meta.userdata_addr_range()[0]
if addr < 0:
print(" Negative write addr: {}".format(addr))
sys.exit(1)
if not fpga.is_bootloader_active():
print(" Bootloader not active")
sys.exit(1)
if check_if_overwrite_bootloader(
addr, len(bitstream),
fpga.meta.userdata_addr_range()):
boot_fpga = True
print(" Programming at addr {:06x}".format(addr))
if not fpga.program_bitstream(addr, bitstream):
sys.exit(1)
# program user image and data area
if args.program_image is not None:
print(" Programming %s with %s" % (
active_port, args.program_image))
bitstream = fpga.slurp(args.program_image)
if args.addr is not None:
addr = parse_int(args.addr)
else:
addr = fpga.meta.userimage_addr_range()[0]
if addr < 0:
print(" Negative write addr: {}".format(addr))
sys.exit(1)
if not fpga.is_bootloader_active():
print(" Bootloader not active")
sys.exit(1)
if check_if_overwrite_bootloader(
addr, len(bitstream),
(fpga.meta.userimage_addr_range()[0],
fpga.meta.userdata_addr_range()[1])):
boot_fpga = True
print(" Programming at addr {:06x}".format(addr))
if not fpga.program_bitstream(addr, bitstream):
sys.exit(1)
if boot_fpga:
fpga.boot()
print("")
sys.exit(0)
# boot the FPGA
if args.boot:
print(" Booting " + str(active_port))
with active_port:
fpga = TinyProg(active_port)
fpga.boot()
except PortError as e:
print(str(e), file=sys.stderr)
sys.exit(1)
print("")
if __name__ == '__main__':
main()