Skip to content

Commit 59b6099

Browse files
committed
tools/uf2conv.py: Update to latest version.
Signed-off-by: Damien George <[email protected]>
1 parent feeeb5e commit 59b6099

File tree

2 files changed

+291
-30
lines changed

2 files changed

+291
-30
lines changed

tools/uf2conv.py

100755100644
+99-30
Original file line numberDiff line numberDiff line change
@@ -33,21 +33,13 @@
3333
import os
3434
import os.path
3535
import argparse
36+
import json
3637

3738

3839
UF2_MAGIC_START0 = 0x0A324655 # "UF2\n"
3940
UF2_MAGIC_START1 = 0x9E5D5157 # Randomly selected
4041
UF2_MAGIC_END = 0x0AB16F30 # Ditto
4142

42-
families = {
43-
"SAMD21": 0x68ED2B88,
44-
"SAMD51": 0x55114460,
45-
"NRF52": 0x1B57745F,
46-
"STM32F1": 0x5EE21072,
47-
"STM32F4": 0x57755A57,
48-
"ATMEGA32": 0x16573617,
49-
}
50-
5143
INFO_FILE = "/INFO_UF2.TXT"
5244

5345
appstartaddr = 0x2000
@@ -71,9 +63,14 @@ def is_hex(buf):
7163

7264
def convert_from_uf2(buf):
7365
global appstartaddr
66+
global familyid
7467
numblocks = len(buf) // 512
7568
curraddr = None
76-
outp = b""
69+
currfamilyid = None
70+
families_found = {}
71+
prev_flag = None
72+
all_flags_same = True
73+
outp = []
7774
for blockno in range(numblocks):
7875
ptr = blockno * 512
7976
block = buf[ptr : ptr + 512]
@@ -88,9 +85,13 @@ def convert_from_uf2(buf):
8885
if datalen > 476:
8986
assert False, "Invalid UF2 data size at " + ptr
9087
newaddr = hd[3]
91-
if curraddr == None:
92-
appstartaddr = newaddr
88+
if (hd[2] & 0x2000) and (currfamilyid == None):
89+
currfamilyid = hd[7]
90+
if curraddr == None or ((hd[2] & 0x2000) and hd[7] != currfamilyid):
91+
currfamilyid = hd[7]
9392
curraddr = newaddr
93+
if familyid == 0x0 or familyid == hd[7]:
94+
appstartaddr = newaddr
9495
padding = newaddr - curraddr
9596
if padding < 0:
9697
assert False, "Block out of order at " + ptr
@@ -101,19 +102,53 @@ def convert_from_uf2(buf):
101102
while padding > 0:
102103
padding -= 4
103104
outp += b"\x00\x00\x00\x00"
104-
outp += block[32 : 32 + datalen]
105+
if familyid == 0x0 or ((hd[2] & 0x2000) and familyid == hd[7]):
106+
outp.append(block[32 : 32 + datalen])
105107
curraddr = newaddr + datalen
106-
return outp
108+
if hd[2] & 0x2000:
109+
if hd[7] in families_found.keys():
110+
if families_found[hd[7]] > newaddr:
111+
families_found[hd[7]] = newaddr
112+
else:
113+
families_found[hd[7]] = newaddr
114+
if prev_flag == None:
115+
prev_flag = hd[2]
116+
if prev_flag != hd[2]:
117+
all_flags_same = False
118+
if blockno == (numblocks - 1):
119+
print("--- UF2 File Header Info ---")
120+
families = load_families()
121+
for family_hex in families_found.keys():
122+
family_short_name = ""
123+
for name, value in families.items():
124+
if value == family_hex:
125+
family_short_name = name
126+
print(
127+
"Family ID is {:s}, hex value is 0x{:08x}".format(
128+
family_short_name, family_hex
129+
)
130+
)
131+
print("Target Address is 0x{:08x}".format(families_found[family_hex]))
132+
if all_flags_same:
133+
print("All block flag values consistent, 0x{:04x}".format(hd[2]))
134+
else:
135+
print("Flags were not all the same")
136+
print("----------------------------")
137+
if len(families_found) > 1 and familyid == 0x0:
138+
outp = []
139+
appstartaddr = 0x0
140+
return b"".join(outp)
107141

108142

109143
def convert_to_carray(file_content):
110-
outp = "const unsigned char bindata[] __attribute__((aligned(16))) = {"
144+
outp = "const unsigned long bindata_len = %d;\n" % len(file_content)
145+
outp += "const unsigned char bindata[] __attribute__((aligned(16))) = {"
111146
for i in range(len(file_content)):
112147
if i % 16 == 0:
113148
outp += "\n"
114-
outp += "0x%02x, " % ord(file_content[i])
149+
outp += "0x%02x, " % file_content[i]
115150
outp += "\n};\n"
116-
return outp
151+
return bytes(outp, "utf-8")
117152

118153

119154
def convert_to_uf2(file_content):
@@ -122,7 +157,7 @@ def convert_to_uf2(file_content):
122157
while len(datapadding) < 512 - 256 - 32 - 4:
123158
datapadding += b"\x00\x00\x00\x00"
124159
numblocks = (len(file_content) + 255) // 256
125-
outp = b""
160+
outp = []
126161
for blockno in range(numblocks):
127162
ptr = 256 * blockno
128163
chunk = file_content[ptr : ptr + 256]
@@ -144,8 +179,8 @@ def convert_to_uf2(file_content):
144179
chunk += b"\x00"
145180
block = hd + chunk + datapadding + struct.pack(b"<I", UF2_MAGIC_END)
146181
assert len(block) == 512
147-
outp += block
148-
return outp
182+
outp.append(block)
183+
return b"".join(outp)
149184

150185

151186
class Block:
@@ -195,11 +230,10 @@ def convert_from_hex_to_uf2(buf):
195230
upper = ((rec[4] << 8) | rec[5]) << 16
196231
elif tp == 2:
197232
upper = ((rec[4] << 8) | rec[5]) << 4
198-
assert (upper & 0xFFFF) == 0
199233
elif tp == 1:
200234
break
201235
elif tp == 0:
202-
addr = upper | (rec[1] << 8) | rec[2]
236+
addr = upper + ((rec[1] << 8) | rec[2])
203237
if appstartaddr == None:
204238
appstartaddr = addr
205239
i = 4
@@ -217,6 +251,10 @@ def convert_from_hex_to_uf2(buf):
217251
return resfile
218252

219253

254+
def to_str(b):
255+
return b.decode("utf-8")
256+
257+
220258
def get_drives():
221259
drives = []
222260
if sys.platform == "win32":
@@ -232,7 +270,7 @@ def get_drives():
232270
"DriveType",
233271
]
234272
)
235-
for line in r.split("\n"):
273+
for line in to_str(r).split("\n"):
236274
words = re.split("\s+", line)
237275
if len(words) >= 3 and words[1] == "2" and words[2] == "FAT":
238276
drives.append(words[0])
@@ -270,7 +308,23 @@ def list_drives():
270308
def write_file(name, buf):
271309
with open(name, "wb") as f:
272310
f.write(buf)
273-
print("Wrote %d bytes to %s." % (len(buf), name))
311+
print("Wrote %d bytes to %s" % (len(buf), name))
312+
313+
314+
def load_families():
315+
# The expectation is that the `uf2families.json` file is in the same
316+
# directory as this script. Make a path that works using `__file__`
317+
# which contains the full path to this script.
318+
filename = "uf2families.json"
319+
pathname = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)
320+
with open(pathname) as f:
321+
raw_families = json.load(f)
322+
323+
families = {}
324+
for family in raw_families:
325+
families[family["short_name"]] = int(family["id"], 0)
326+
327+
return families
274328

275329

276330
def main():
@@ -303,6 +357,7 @@ def error(msg):
303357
parser.add_argument("-d", "--device", dest="device_path", help="select a device path to flash")
304358
parser.add_argument("-l", "--list", action="store_true", help="list connected devices")
305359
parser.add_argument("-c", "--convert", action="store_true", help="do not flash, just convert")
360+
parser.add_argument("-D", "--deploy", action="store_true", help="just flash, do not convert")
306361
parser.add_argument(
307362
"-f",
308363
"--family",
@@ -314,9 +369,17 @@ def error(msg):
314369
parser.add_argument(
315370
"-C", "--carray", action="store_true", help="convert binary file to a C array, not UF2"
316371
)
372+
parser.add_argument(
373+
"-i",
374+
"--info",
375+
action="store_true",
376+
help="display header information from UF2, do not convert",
377+
)
317378
args = parser.parse_args()
318379
appstartaddr = int(args.base, 0)
319380

381+
families = load_families()
382+
320383
if args.family.upper() in families:
321384
familyid = families[args.family.upper()]
322385
else:
@@ -334,21 +397,27 @@ def error(msg):
334397
inpbuf = f.read()
335398
from_uf2 = is_uf2(inpbuf)
336399
ext = "uf2"
337-
if from_uf2:
400+
if args.deploy:
401+
outbuf = inpbuf
402+
elif from_uf2 and not args.info:
338403
outbuf = convert_from_uf2(inpbuf)
339404
ext = "bin"
405+
elif from_uf2 and args.info:
406+
outbuf = ""
407+
convert_from_uf2(inpbuf)
340408
elif is_hex(inpbuf):
341409
outbuf = convert_from_hex_to_uf2(inpbuf.decode("utf-8"))
342410
elif args.carray:
343411
outbuf = convert_to_carray(inpbuf)
344412
ext = "h"
345413
else:
346414
outbuf = convert_to_uf2(inpbuf)
347-
print(
348-
"Converting to %s, output size: %d, start address: 0x%x"
349-
% (ext, len(outbuf), appstartaddr)
350-
)
351-
if args.convert:
415+
if not args.deploy and not args.info:
416+
print(
417+
"Converted to %s, output size: %d, start address: 0x%x"
418+
% (ext, len(outbuf), appstartaddr)
419+
)
420+
if args.convert or ext != "uf2":
352421
drives = []
353422
if args.output == None:
354423
args.output = "flash." + ext

0 commit comments

Comments
 (0)