toprammer 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. #!/usr/bin/env python3
  2. """
  3. # TOP2049 Open Source programming suite
  4. #
  5. # Commandline utility
  6. #
  7. # Copyright (c) 2009-2013 Michael Buesch <m@bues.ch>
  8. #
  9. # This program is free software; you can redistribute it and/or modify
  10. # it under the terms of the GNU General Public License as published by
  11. # the Free Software Foundation; either version 2 of the License, or
  12. # (at your option) any later version.
  13. #
  14. # This program is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. # GNU General Public License for more details.
  18. #
  19. # You should have received a copy of the GNU General Public License along
  20. # with this program; if not, write to the Free Software Foundation, Inc.,
  21. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  22. """
  23. from libtoprammer.main import *
  24. from libtoprammer.util import *
  25. import getopt
  26. def usage():
  27. print("TOP2049 Open Source programming suite v%s" % VERSION)
  28. print("")
  29. print("Usage: %s [OPTIONS] [ACTIONS]" % sys.argv[0])
  30. print("")
  31. print(" -c|--chip-id The ID of the handled chip. (mandatory)")
  32. print(" See -t|--list for a list of supported chips.")
  33. print("")
  34. print("Optional:")
  35. print(" -C|--chip-opt NAME=VAL Set a chip-id specific option.")
  36. print(" Use -c CHIPID -t to get a list of options.")
  37. print("")
  38. print("Actions:")
  39. print(" -s|--read-sig FILE Read the signature bytes")
  40. print(" -x|--erase Erase the chip")
  41. print(" -T|--test Run chip unit-test")
  42. print("")
  43. print(" -p|--read-prog FILE Read the program memory")
  44. print(" -P|--write-prog FILE Write the program memory")
  45. print("")
  46. print(" -e|--read-eeprom FILE Read the EEPROM")
  47. print(" -E|--write-eeprom FILE Write the EEPROM")
  48. print("")
  49. print(" -f|--read-fuse FILE Read the fuse bits")
  50. print(" -F|--write-fuse FILE Write the fuse bits")
  51. print("")
  52. print(" -l|--read-lock FILE Read the lock bits")
  53. print(" -L|--write-lock FILE Write the lock bits")
  54. print("")
  55. print(" -r|--read-ram FILE Read the RAM")
  56. print(" -R|--write-ram FILE Write the RAM")
  57. print("")
  58. print(" -a|--read-uil FILE Read the User ID Location")
  59. print(" -A|--write-uil FILE Write the User ID Location")
  60. print("")
  61. print("Other options:")
  62. print(" -t|--list Print a list of supported chips and exit.")
  63. print(" Use -V|--verbose to control the list verbosity (0-4)")
  64. print(" -d|--device DEVID Use a specific programmer. Example for USB:")
  65. print(" usb:TOP2049:0")
  66. print(" First found programmer is used, if not given.")
  67. print(" -V|--verbose LEVEL Set the verbosity level:")
  68. print(" 0 => show warnings")
  69. print(" 1 => also show informational messages (default)")
  70. print(" 2 => also show debugging messages")
  71. print(" 3 => also dump all USB commands")
  72. print(" -o|--force LEVEL Set the force level. Default = 0")
  73. print(" Note that any value greater than 0 may brick devices")
  74. print(" -U|--force-upload Force upload the bitfile, even if it already appears")
  75. print(" to be uploaded.")
  76. print(" -Q|--noqueue Disable command queuing. Really slow!")
  77. print(" -B|--broken Also use broken algorithms")
  78. print(" -I|--in-format FMT Input file format. Default = autodetect")
  79. print(" -O|--out-format FMT Output file format. Default = bin")
  80. print("")
  81. print("File formats (FMT):")
  82. print(" auto Autodetect. (input only)")
  83. print(" bin Raw binary data")
  84. print(" ihex Intel hex")
  85. print(" ihex-raw Raw Intel hex (don't interpret sections)")
  86. print(" ahex Hex with ASCII dump")
  87. IO_handlers = {
  88. "bin" : IO_binary,
  89. "ihex" : IO_ihex,
  90. "ihex-raw" : IO_ihex,
  91. "ahex" : IO_ahex,
  92. }
  93. def fileOut(filename, fmtString, data):
  94. handler = IO_handlers[fmtString]()
  95. data = handler.fromBinary(data)
  96. if isinstance(data, str):
  97. data = data.encode("UTF-8")
  98. if filename == "-":
  99. sys.stdout.buffer.write(data)
  100. else:
  101. with open(filename, "w+b") as f:
  102. f.write(data)
  103. def fileIn(top, action, filename, fmtString):
  104. if filename == "-":
  105. data = sys.stdin.buffer.read()
  106. else:
  107. with open(filename, "rb") as f:
  108. data = f.read()
  109. if fmtString == "auto":
  110. handler = IO_autodetect(data)()
  111. else:
  112. handler = IO_handlers[fmtString]()
  113. if isinstance(handler, IO_ihex):
  114. interp = top.getChip().getIHexInterpreter()
  115. interp.interpret(data)
  116. if interp.cumulativeSupported():
  117. readRaw = fmtString.endswith("-raw")
  118. else:
  119. readRaw = True
  120. if action == "write-prog":
  121. binData = interp.getProgmem(dontInterpretSections = readRaw)
  122. elif action == "write-eeprom":
  123. binData = interp.getEEPROM(dontInterpretSections = readRaw)
  124. elif action == "write-fuse":
  125. binData = interp.getFusebits(dontInterpretSections = readRaw)
  126. elif action == "write-lock":
  127. binData = interp.getLockbits(dontInterpretSections = readRaw)
  128. elif action == "write-ram":
  129. binData = interp.getRAM(dontInterpretSections = readRaw)
  130. elif action == "write-uil":
  131. binData = interp.getUIL(dontInterpretSections = readRaw)
  132. else:
  133. assert(0)
  134. return binData
  135. return handler.toBinary(data)
  136. def main(argv):
  137. opt_verbose = 1
  138. opt_forceLevel = 0
  139. opt_forceBitfileUpload = False
  140. opt_chipID = None
  141. opt_chipOptions = []
  142. opt_device = None
  143. opt_action = None
  144. opt_file = None
  145. opt_noqueue = False
  146. opt_usebroken = False
  147. opt_informat = "auto"
  148. opt_outformat = "bin"
  149. try:
  150. (opts, args) = getopt.getopt(sys.argv[1:],
  151. "hc:d:V:Qs:xTp:P:e:E:f:F:o:Ul:L:r:R:BtI:O:C:a:A:",
  152. [ "help", "chip-id=", "device=", "verbose=", "noqueue",
  153. "read-sig=", "erase", "test", "read-prog=", "write-prog=",
  154. "read-eeprom=", "write-eeprom=", "read-fuse=", "write-fuse=",
  155. "read-lock=", "write-lock=", "read-ram=", "write-ram=",
  156. "force=", "force-upload", "broken", "list",
  157. "in-format=", "out-format=", "chip-opt=",
  158. "read-uil=", "write-uil=" ])
  159. for (o, v) in opts:
  160. if o in ("-h", "--help"):
  161. usage()
  162. return 0
  163. if o in ("-c", "--chip-id"):
  164. opt_chipID = v
  165. if o in ("-C", "--chip-opt"):
  166. try:
  167. v = v.split('=')
  168. name, value = v[0], v[1]
  169. except (IndexError, ValueError) as e:
  170. print("-C|--chip-opt invalid parameter")
  171. return 1
  172. copt = AssignedChipOption(name, value)
  173. opt_chipOptions.append(copt)
  174. if o in ("-t", "--list"):
  175. opt_action = "print-list"
  176. if o in ("-d", "--device"):
  177. opt_device = v
  178. if o in ("-V", "--verbose"):
  179. opt_verbose = int(v)
  180. if o in ("-o", "--force"):
  181. opt_forceLevel = int(v)
  182. if o in ("-U", "--force-upload"):
  183. opt_forceBitfileUpload = True
  184. if o in ("-Q", "--noqueue"):
  185. opt_noqueue = True
  186. if o in ("-B", "--broken"):
  187. opt_usebroken = True
  188. if o in ("-I", "--in-format"):
  189. opt_informat = v.lower()
  190. if o in ("-O", "--out-format"):
  191. opt_outformat = v.lower()
  192. if o in ("-s", "--read-sig"):
  193. opt_action = "read-sig"
  194. opt_file = v
  195. if o in ("-x", "--erase"):
  196. opt_action = "erase"
  197. if o in ("-T", "--test"):
  198. opt_action = "test"
  199. if o in ("-P", "--write-prog"):
  200. opt_action = "write-prog"
  201. opt_file = v
  202. if o in ("-p", "--read-prog"):
  203. opt_action = "read-prog"
  204. opt_file = v
  205. if o in ("-E", "--write-eeprom"):
  206. opt_action = "write-eeprom"
  207. opt_file = v
  208. if o in ("-e", "--read-eeprom"):
  209. opt_action = "read-eeprom"
  210. opt_file = v
  211. if o in ("-F", "--write-fuse"):
  212. opt_action = "write-fuse"
  213. opt_file = v
  214. if o in ("-f", "--read-fuse"):
  215. opt_action = "read-fuse"
  216. opt_file = v
  217. if o in ("-l", "--read-lock"):
  218. opt_action = "read-lock"
  219. opt_file = v
  220. if o in ("-L", "--write-lock"):
  221. opt_action = "write-lock"
  222. opt_file = v
  223. if o in ("-r", "--read-ram"):
  224. opt_action = "read-ram"
  225. opt_file = v
  226. if o in ("-R", "--write-ram"):
  227. opt_action = "write-ram"
  228. opt_file = v
  229. if o in ("-a", "--read-uil"):
  230. opt_action = "read-uil"
  231. opt_file = v
  232. if o in ("-A", "--write-uil"):
  233. opt_action = "write-uil"
  234. opt_file = v
  235. except (getopt.GetoptError, ValueError) as e:
  236. usage()
  237. return 1
  238. if opt_action != "print-list" and not opt_chipID:
  239. print("-c|--chip-id is mandatory!")
  240. return 1
  241. if not opt_informat in ("auto", "bin", "ihex", "ihex-raw", "ahex"):
  242. print("Invalid -I|--in-format")
  243. return 1
  244. if not opt_outformat in ("bin", "ihex", "ihex-raw", "ahex"):
  245. print("Invalid -O|--out-format")
  246. return 1
  247. try:
  248. if opt_action == "print-list":
  249. if opt_chipID:
  250. desc = ChipDescription.findOne(opt_chipID, True)
  251. desc.dump(sys.stdout, verbose=opt_verbose)
  252. else:
  253. ChipDescription.dumpAll(sys.stdout,
  254. verbose=opt_verbose, showBroken=True)
  255. return 0
  256. top = TOP(devIdentifier = opt_device,
  257. verbose = opt_verbose, forceLevel = opt_forceLevel,
  258. noqueue = opt_noqueue, usebroken = opt_usebroken,
  259. forceBitfileUpload = opt_forceBitfileUpload)
  260. top.initializeChip(chipID = opt_chipID,
  261. assignedChipOptions = opt_chipOptions)
  262. if opt_action == "read-sig":
  263. fileOut(opt_file, opt_outformat, top.readSignature())
  264. elif opt_action == "erase":
  265. top.eraseChip()
  266. elif opt_action == "test":
  267. top.testChip()
  268. elif opt_action == "read-prog":
  269. fileOut(opt_file, opt_outformat, top.readProgmem())
  270. elif opt_action == "write-prog":
  271. image = fileIn(top, opt_action, opt_file, opt_informat)
  272. top.writeProgmem(image)
  273. elif opt_action == "read-eeprom":
  274. fileOut(opt_file, opt_outformat, top.readEEPROM())
  275. elif opt_action == "write-eeprom":
  276. top.writeEEPROM(fileIn(top, opt_action, opt_file, opt_informat))
  277. elif opt_action == "read-fuse":
  278. fileOut(opt_file, opt_outformat, top.readFuse())
  279. elif opt_action == "write-fuse":
  280. image = fileIn(top, opt_action, opt_file, opt_informat)
  281. top.writeFuse(image)
  282. elif opt_action == "read-lock":
  283. fileOut(opt_file, opt_outformat, top.readLockbits())
  284. elif opt_action == "write-lock":
  285. top.writeLockbits(fileIn(top, opt_action, opt_file, opt_informat))
  286. elif opt_action == "read-ram":
  287. fileOut(opt_file, opt_outformat, top.readRAM())
  288. elif opt_action == "write-ram":
  289. top.writeRAM(fileIn(top, opt_action, opt_file, opt_informat))
  290. elif opt_action == "read-uil":
  291. fileOut(opt_file, opt_outformat, top.readUserIdLocation())
  292. elif opt_action == "write-uil":
  293. top.writeUserIdLocation(fileIn(top, opt_action, opt_file, opt_informat))
  294. else:
  295. if opt_verbose >= 1:
  296. print("No action specified")
  297. top.shutdownChip()
  298. except (TOPException, BitfileException, IOError) as e:
  299. print(e)
  300. return 1
  301. return 0
  302. if __name__ == "__main__":
  303. sys.exit(main(sys.argv))