update.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. # greaseweazle/tools/update.py
  2. #
  3. # Greaseweazle control script: Firmware Update.
  4. #
  5. # Written & released by Keir Fraser <keir.xen@gmail.com>
  6. #
  7. # This is free and unencumbered software released into the public domain.
  8. # See the file COPYING for more details, or visit <http://unlicense.org>.
  9. import sys, argparse, serial, struct
  10. import crcmod.predefined
  11. from greaseweazle.tools import util
  12. from greaseweazle import usb as USB
  13. # update_firmware:
  14. # Updates the Greaseweazle firmware using the specified Update File.
  15. def update_firmware(usb, args):
  16. # Read the entire update catalogue.
  17. with open(args.file, "rb") as f:
  18. dat = f.read()
  19. # Search the catalogue for a match on our Weazle's hardware type.
  20. while dat:
  21. upd_len, hw_type = struct.unpack("<2H", dat[:4])
  22. if hw_type == usb.hw_type:
  23. # Match: Pull out the embedded update file.
  24. dat = dat[4:upd_len+4]
  25. break
  26. # Skip to the next catalogue entry.
  27. dat = dat[upd_len+4:]
  28. if not dat:
  29. print("%s: No match for hardware type %x" % (args.file, usb.hw_type))
  30. return
  31. # Check the matching update file's footer.
  32. sig, maj, min, hw_type = struct.unpack("<2s2BH", dat[-8:-2])
  33. if len(dat) & 3 != 0 or sig != b'GW' or hw_type != usb.hw_type:
  34. print("%s: Bad update file" % (args.file))
  35. return
  36. crc16 = crcmod.predefined.Crc('crc-ccitt-false')
  37. crc16.update(dat)
  38. if crc16.crcValue != 0:
  39. print("%s: Bad CRC" % (args.file))
  40. return
  41. # Perform the update.
  42. print("Updating to v%u.%u..." % (maj, min))
  43. ack = usb.update_firmware(dat)
  44. if ack != 0:
  45. print("** UPDATE FAILED: Please retry!")
  46. return
  47. print("Done.")
  48. if usb.hw_type == 7:
  49. util.usb_reopen(usb, is_update=False)
  50. else:
  51. print("** Disconnect Greaseweazle and remove the Programming Jumper.")
  52. def main(argv):
  53. parser = argparse.ArgumentParser(
  54. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  55. parser.add_argument("file", help="update filename")
  56. parser.add_argument("device", nargs="?", default="auto",
  57. help="serial device")
  58. parser.prog += ' ' + argv[1]
  59. args = parser.parse_args(argv[2:])
  60. usb = util.usb_open(args.device, is_update=True)
  61. try:
  62. update_firmware(usb, args)
  63. except USB.CmdError as error:
  64. print("Command Failed: %s" % error)
  65. if __name__ == "__main__":
  66. main(sys.argv)
  67. # Local variables:
  68. # python-indent: 4
  69. # End: