uf2conv.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. #!/usr/bin/env python3
  2. import sys
  3. import struct
  4. import subprocess
  5. import re
  6. import os
  7. import os.path
  8. import argparse
  9. import json
  10. UF2_MAGIC_START0 = 0x0A324655 # "UF2\n"
  11. UF2_MAGIC_START1 = 0x9E5D5157 # Randomly selected
  12. UF2_MAGIC_END = 0x0AB16F30 # Ditto
  13. INFO_FILE = "/INFO_UF2.TXT"
  14. appstartaddr = 0x2000
  15. familyid = 0x0
  16. def is_uf2(buf):
  17. w = struct.unpack("<II", buf[0:8])
  18. return w[0] == UF2_MAGIC_START0 and w[1] == UF2_MAGIC_START1
  19. def is_hex(buf):
  20. try:
  21. w = buf[0:30].decode("utf-8")
  22. except UnicodeDecodeError:
  23. return False
  24. if w[0] == ':' and re.match(b"^[:0-9a-fA-F\r\n]+$", buf):
  25. return True
  26. return False
  27. def convert_from_uf2(buf):
  28. global appstartaddr
  29. global familyid
  30. numblocks = len(buf) // 512
  31. curraddr = None
  32. currfamilyid = None
  33. families_found = {}
  34. prev_flag = None
  35. all_flags_same = True
  36. outp = []
  37. for blockno in range(numblocks):
  38. ptr = blockno * 512
  39. block = buf[ptr:ptr + 512]
  40. hd = struct.unpack(b"<IIIIIIII", block[0:32])
  41. if hd[0] != UF2_MAGIC_START0 or hd[1] != UF2_MAGIC_START1:
  42. print("Skipping block at " + ptr + "; bad magic")
  43. continue
  44. if hd[2] & 1:
  45. # NO-flash flag set; skip block
  46. continue
  47. datalen = hd[4]
  48. if datalen > 476:
  49. assert False, "Invalid UF2 data size at " + ptr
  50. newaddr = hd[3]
  51. if (hd[2] & 0x2000) and (currfamilyid == None):
  52. currfamilyid = hd[7]
  53. if curraddr == None or ((hd[2] & 0x2000) and hd[7] != currfamilyid):
  54. currfamilyid = hd[7]
  55. curraddr = newaddr
  56. if familyid == 0x0 or familyid == hd[7]:
  57. appstartaddr = newaddr
  58. padding = newaddr - curraddr
  59. if padding < 0:
  60. assert False, "Block out of order at " + ptr
  61. if padding > 10*1024*1024:
  62. assert False, "More than 10M of padding needed at " + ptr
  63. if padding % 4 != 0:
  64. assert False, "Non-word padding size at " + ptr
  65. while padding > 0:
  66. padding -= 4
  67. outp += b"\x00\x00\x00\x00"
  68. if familyid == 0x0 or ((hd[2] & 0x2000) and familyid == hd[7]):
  69. outp.append(block[32 : 32 + datalen])
  70. curraddr = newaddr + datalen
  71. if hd[2] & 0x2000:
  72. if hd[7] in families_found.keys():
  73. if families_found[hd[7]] > newaddr:
  74. families_found[hd[7]] = newaddr
  75. else:
  76. families_found[hd[7]] = newaddr
  77. if prev_flag == None:
  78. prev_flag = hd[2]
  79. if prev_flag != hd[2]:
  80. all_flags_same = False
  81. if blockno == (numblocks - 1):
  82. print("--- UF2 File Header Info ---")
  83. families = load_families()
  84. for family_hex in families_found.keys():
  85. family_short_name = ""
  86. for name, value in families.items():
  87. if value == family_hex:
  88. family_short_name = name
  89. print("Family ID is {:s}, hex value is 0x{:08x}".format(family_short_name,family_hex))
  90. print("Target Address is 0x{:08x}".format(families_found[family_hex]))
  91. if all_flags_same:
  92. print("All block flag values consistent, 0x{:04x}".format(hd[2]))
  93. else:
  94. print("Flags were not all the same")
  95. print("----------------------------")
  96. if len(families_found) > 1 and familyid == 0x0:
  97. outp = []
  98. appstartaddr = 0x0
  99. return b"".join(outp)
  100. def convert_to_carray(file_content):
  101. outp = "const unsigned long bindata_len = %d;\n" % len(file_content)
  102. outp += "const unsigned char bindata[] __attribute__((aligned(16))) = {"
  103. for i in range(len(file_content)):
  104. if i % 16 == 0:
  105. outp += "\n"
  106. outp += "0x%02x, " % file_content[i]
  107. outp += "\n};\n"
  108. return bytes(outp, "utf-8")
  109. def convert_to_uf2(file_content):
  110. global familyid
  111. datapadding = b""
  112. while len(datapadding) < 512 - 256 - 32 - 4:
  113. datapadding += b"\x00\x00\x00\x00"
  114. numblocks = (len(file_content) + 255) // 256
  115. outp = []
  116. for blockno in range(numblocks):
  117. ptr = 256 * blockno
  118. chunk = file_content[ptr:ptr + 256]
  119. flags = 0x0
  120. if familyid:
  121. flags |= 0x2000
  122. hd = struct.pack(b"<IIIIIIII",
  123. UF2_MAGIC_START0, UF2_MAGIC_START1,
  124. flags, ptr + appstartaddr, 256, blockno, numblocks, familyid)
  125. while len(chunk) < 256:
  126. chunk += b"\x00"
  127. block = hd + chunk + datapadding + struct.pack(b"<I", UF2_MAGIC_END)
  128. assert len(block) == 512
  129. outp.append(block)
  130. return b"".join(outp)
  131. class Block:
  132. def __init__(self, addr):
  133. self.addr = addr
  134. self.bytes = bytearray(256)
  135. def encode(self, blockno, numblocks):
  136. global familyid
  137. flags = 0x0
  138. if familyid:
  139. flags |= 0x2000
  140. hd = struct.pack("<IIIIIIII",
  141. UF2_MAGIC_START0, UF2_MAGIC_START1,
  142. flags, self.addr, 256, blockno, numblocks, familyid)
  143. hd += self.bytes[0:256]
  144. while len(hd) < 512 - 4:
  145. hd += b"\x00"
  146. hd += struct.pack("<I", UF2_MAGIC_END)
  147. return hd
  148. def convert_from_hex_to_uf2(buf):
  149. global appstartaddr
  150. appstartaddr = None
  151. upper = 0
  152. currblock = None
  153. blocks = []
  154. for line in buf.split('\n'):
  155. if line[0] != ":":
  156. continue
  157. i = 1
  158. rec = []
  159. while i < len(line) - 1:
  160. rec.append(int(line[i:i+2], 16))
  161. i += 2
  162. tp = rec[3]
  163. if tp == 4:
  164. upper = ((rec[4] << 8) | rec[5]) << 16
  165. elif tp == 2:
  166. upper = ((rec[4] << 8) | rec[5]) << 4
  167. elif tp == 1:
  168. break
  169. elif tp == 0:
  170. addr = upper + ((rec[1] << 8) | rec[2])
  171. if appstartaddr == None:
  172. appstartaddr = addr
  173. i = 4
  174. while i < len(rec) - 1:
  175. if not currblock or currblock.addr & ~0xff != addr & ~0xff:
  176. currblock = Block(addr & ~0xff)
  177. blocks.append(currblock)
  178. currblock.bytes[addr & 0xff] = rec[i]
  179. addr += 1
  180. i += 1
  181. numblocks = len(blocks)
  182. resfile = b""
  183. for i in range(0, numblocks):
  184. resfile += blocks[i].encode(i, numblocks)
  185. return resfile
  186. def to_str(b):
  187. return b.decode("utf-8")
  188. def get_drives():
  189. drives = []
  190. if sys.platform == "win32":
  191. r = subprocess.check_output(["wmic", "PATH", "Win32_LogicalDisk",
  192. "get", "DeviceID,", "VolumeName,",
  193. "FileSystem,", "DriveType"])
  194. for line in to_str(r).split('\n'):
  195. words = re.split('\s+', line)
  196. if len(words) >= 3 and words[1] == "2" and words[2] == "FAT":
  197. drives.append(words[0])
  198. else:
  199. rootpath = "/media"
  200. if sys.platform == "darwin":
  201. rootpath = "/Volumes"
  202. elif sys.platform == "linux":
  203. tmp = rootpath + "/" + os.environ["USER"]
  204. if os.path.isdir(tmp):
  205. rootpath = tmp
  206. for d in os.listdir(rootpath):
  207. drives.append(os.path.join(rootpath, d))
  208. def has_info(d):
  209. try:
  210. return os.path.isfile(d + INFO_FILE)
  211. except:
  212. return False
  213. return list(filter(has_info, drives))
  214. def board_id(path):
  215. with open(path + INFO_FILE, mode='r') as file:
  216. file_content = file.read()
  217. return re.search("Board-ID: ([^\r\n]*)", file_content).group(1)
  218. def list_drives():
  219. for d in get_drives():
  220. print(d, board_id(d))
  221. def write_file(name, buf):
  222. with open(name, "wb") as f:
  223. f.write(buf)
  224. print("Wrote %d bytes to %s" % (len(buf), name))
  225. def load_families():
  226. # The expectation is that the `uf2families.json` file is in the same
  227. # directory as this script. Make a path that works using `__file__`
  228. # which contains the full path to this script.
  229. filename = "uf2families.json"
  230. pathname = os.path.join(os.path.dirname(os.path.abspath(__file__)), filename)
  231. with open(pathname) as f:
  232. raw_families = json.load(f)
  233. families = {}
  234. for family in raw_families:
  235. families[family["short_name"]] = int(family["id"], 0)
  236. return families
  237. def main():
  238. global appstartaddr, familyid
  239. def error(msg):
  240. print(msg, file=sys.stderr)
  241. sys.exit(1)
  242. parser = argparse.ArgumentParser(description='Convert to UF2 or flash directly.')
  243. parser.add_argument('input', metavar='INPUT', type=str, nargs='?',
  244. help='input file (HEX, BIN or UF2)')
  245. parser.add_argument('-b' , '--base', dest='base', type=str,
  246. default="0x2000",
  247. help='set base address of application for BIN format (default: 0x2000)')
  248. parser.add_argument('-o' , '--output', metavar="FILE", dest='output', type=str,
  249. help='write output to named file; defaults to "flash.uf2" or "flash.bin" where sensible')
  250. parser.add_argument('-d' , '--device', dest="device_path",
  251. help='select a device path to flash')
  252. parser.add_argument('-l' , '--list', action='store_true',
  253. help='list connected devices')
  254. parser.add_argument('-c' , '--convert', action='store_true',
  255. help='do not flash, just convert')
  256. parser.add_argument('-D' , '--deploy', action='store_true',
  257. help='just flash, do not convert')
  258. parser.add_argument('-f' , '--family', dest='family', type=str,
  259. default="0x0",
  260. help='specify familyID - number or name (default: 0x0)')
  261. parser.add_argument('-C' , '--carray', action='store_true',
  262. help='convert binary file to a C array, not UF2')
  263. parser.add_argument('-i', '--info', action='store_true',
  264. help='display header information from UF2, do not convert')
  265. args = parser.parse_args()
  266. appstartaddr = int(args.base, 0)
  267. families = load_families()
  268. if args.family.upper() in families:
  269. familyid = families[args.family.upper()]
  270. else:
  271. try:
  272. familyid = int(args.family, 0)
  273. except ValueError:
  274. error("Family ID needs to be a number or one of: " + ", ".join(families.keys()))
  275. if args.list:
  276. list_drives()
  277. else:
  278. if not args.input:
  279. error("Need input file")
  280. with open(args.input, mode='rb') as f:
  281. inpbuf = f.read()
  282. from_uf2 = is_uf2(inpbuf)
  283. ext = "uf2"
  284. if args.deploy:
  285. outbuf = inpbuf
  286. elif from_uf2 and not args.info:
  287. outbuf = convert_from_uf2(inpbuf)
  288. ext = "bin"
  289. elif from_uf2 and args.info:
  290. outbuf = ""
  291. convert_from_uf2(inpbuf)
  292. elif is_hex(inpbuf):
  293. outbuf = convert_from_hex_to_uf2(inpbuf.decode("utf-8"))
  294. elif args.carray:
  295. outbuf = convert_to_carray(inpbuf)
  296. ext = "h"
  297. else:
  298. outbuf = convert_to_uf2(inpbuf)
  299. if not args.deploy and not args.info:
  300. print("Converted to %s, output size: %d, start address: 0x%x" %
  301. (ext, len(outbuf), appstartaddr))
  302. if args.convert or ext != "uf2":
  303. drives = []
  304. if args.output == None:
  305. args.output = "flash." + ext
  306. else:
  307. drives = get_drives()
  308. if args.output:
  309. write_file(args.output, outbuf)
  310. else:
  311. if len(drives) == 0:
  312. error("No drive to deploy.")
  313. for d in drives:
  314. print("Flashing %s (%s)" % (d, board_id(d)))
  315. write_file(d + "/NEW.UF2", outbuf)
  316. if __name__ == "__main__":
  317. main()