util.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. # greaseweazle/tools/util.py
  2. #
  3. # Greaseweazle control script: Utility functions.
  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 argparse, os, sys, serial, struct, time
  10. import importlib
  11. import serial.tools.list_ports
  12. from greaseweazle import version
  13. from greaseweazle import error
  14. from greaseweazle import usb as USB
  15. class CmdlineHelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
  16. def _get_help_string(self, action):
  17. help = action.help
  18. if '%no_default' in help:
  19. return help.replace('%no_default', '')
  20. if ('%(default)' in help
  21. or action.default is None
  22. or action.default is False
  23. or action.default is argparse.SUPPRESS):
  24. return help
  25. return help + ' (default: %(default)s)'
  26. class ArgumentParser(argparse.ArgumentParser):
  27. def __init__(self, formatter_class=CmdlineHelpFormatter, *args, **kwargs):
  28. return super().__init__(formatter_class=formatter_class,
  29. *args, **kwargs)
  30. def drive_letter(letter):
  31. types = {
  32. 'A': (USB.BusType.IBMPC, 0),
  33. 'B': (USB.BusType.IBMPC, 1),
  34. '0': (USB.BusType.Shugart, 0),
  35. '1': (USB.BusType.Shugart, 1),
  36. '2': (USB.BusType.Shugart, 2)
  37. }
  38. if not letter.upper() in types:
  39. raise argparse.ArgumentTypeError("invalid drive letter: '%s'" % letter)
  40. return types[letter.upper()]
  41. def split_opts(seq):
  42. """Splits a name from its list of options."""
  43. parts = seq.split('::')
  44. name, opts = parts[0], dict()
  45. for x in map(lambda x: x.split(':'), parts[1:]):
  46. for y in x:
  47. try:
  48. opt, val = y.split('=')
  49. except ValueError:
  50. opt, val = y, True
  51. if opt:
  52. opts[opt] = val
  53. return name, opts
  54. def get_image_class(name):
  55. image_types = { '.adf': 'ADF',
  56. '.scp': 'SCP',
  57. '.hfe': 'HFE',
  58. '.ipf': 'IPF' }
  59. _, ext = os.path.splitext(name)
  60. error.check(ext.lower() in image_types,
  61. "%s: Unrecognised file suffix '%s'" % (name, ext))
  62. typename = image_types[ext.lower()]
  63. mod = importlib.import_module('greaseweazle.image.' + typename.lower())
  64. return mod.__dict__[typename]
  65. def with_drive_selected(fn, usb, args, *_args, **_kwargs):
  66. usb.set_bus_type(args.drive[0])
  67. try:
  68. usb.drive_select(args.drive[1])
  69. usb.drive_motor(args.drive[1], _kwargs.pop('motor', True))
  70. fn(usb, args, *_args, **_kwargs)
  71. except KeyboardInterrupt:
  72. print()
  73. usb.reset()
  74. usb.ser.close()
  75. usb.ser.open()
  76. raise
  77. finally:
  78. usb.drive_motor(args.drive[1], False)
  79. usb.drive_deselect()
  80. def valid_ser_id(ser_id):
  81. return ser_id and ser_id.upper().startswith("GW")
  82. def score_port(x, old_port=None):
  83. score = 0
  84. if x.manufacturer == "Keir Fraser" and x.product == "Greaseweazle":
  85. score = 20
  86. elif x.vid == 0x1209 and x.pid == 0x4d69:
  87. # Our very own properly-assigned PID. Guaranteed to be us.
  88. score = 20
  89. elif x.vid == 0x1209 and x.pid == 0x0001:
  90. # Our old shared Test PID. It's not guaranteed to be us.
  91. score = 10
  92. if score > 0 and valid_ser_id(x.serial_number):
  93. # A valid serial id is a good sign unless this is a reopen, and
  94. # the serials don't match!
  95. if not old_port or not valid_ser_id(old_port.serial_number):
  96. score = 20
  97. elif x.serial_number == old_port.serial_number:
  98. score = 30
  99. else:
  100. score = 0
  101. if old_port and old_port.location:
  102. # If this is a reopen, location field must match. A match is not
  103. # sufficient in itself however, as Windows may supply the same
  104. # location for multiple USB ports (this may be an interaction with
  105. # BitDefender). Hence we do not increase the port's score here.
  106. if not x.location or x.location != old_port.location:
  107. score = 0
  108. return score
  109. def find_port(old_port=None):
  110. best_score, best_port = 0, None
  111. for x in serial.tools.list_ports.comports():
  112. score = score_port(x, old_port)
  113. if score > best_score:
  114. best_score, best_port = score, x
  115. if best_port:
  116. return best_port.device
  117. raise serial.SerialException('Cannot find the Greaseweazle device')
  118. def port_info(devname):
  119. for x in serial.tools.list_ports.comports():
  120. if x.device == devname:
  121. return x
  122. return None
  123. def usb_reopen(usb, is_update):
  124. mode = { False: 1, True: 0 }
  125. try:
  126. usb.switch_fw_mode(mode[is_update])
  127. except (serial.SerialException, struct.error):
  128. # Mac and Linux raise SerialException ("... returned no data")
  129. # Win10 pyserial returns a short read which fails struct.unpack
  130. pass
  131. usb.ser.close()
  132. for i in range(10):
  133. time.sleep(0.5)
  134. try:
  135. devicename = find_port(usb.port_info)
  136. new_ser = serial.Serial(devicename)
  137. except serial.SerialException:
  138. # Device not found
  139. pass
  140. else:
  141. new_usb = USB.Unit(new_ser)
  142. new_usb.port_info = port_info(devicename)
  143. return new_usb
  144. raise serial.SerialException('Could not reopen port after mode switch')
  145. def usb_open(devicename, is_update=False, mode_check=True):
  146. if devicename is None:
  147. devicename = find_port()
  148. usb = USB.Unit(serial.Serial(devicename))
  149. usb.port_info = port_info(devicename)
  150. if not mode_check:
  151. return usb
  152. if usb.update_mode and not is_update:
  153. if usb.hw_model == 7 and not usb.update_jumpered:
  154. usb = usb_reopen(usb, is_update)
  155. if not usb.update_mode:
  156. return usb
  157. print("Greaseweazle is in Firmware Update Mode:")
  158. print(" The only available action is \"update\" of main firmware")
  159. if usb.update_jumpered:
  160. print(" Remove the Update Jumper for normal operation")
  161. else:
  162. print(" Main firmware is erased: You *must* perform an update!")
  163. sys.exit(1)
  164. if is_update and not usb.update_mode:
  165. if usb.hw_model == 7:
  166. usb = usb_reopen(usb, is_update)
  167. error.check(usb.update_mode, """\
  168. Greaseweazle F7 did not change to Firmware Update Mode as requested.
  169. If the problem persists, install the Update Jumper (across RX/TX).""")
  170. return usb
  171. print("Greaseweazle is in Normal Mode:")
  172. print(" To \"update\" you must install the Update Jumper")
  173. sys.exit(1)
  174. if not usb.update_mode and usb.update_needed:
  175. print("Firmware is out of date: Require v%u.%u"
  176. % (version.major, version.minor))
  177. if usb.hw_model == 7:
  178. print("Run \"update <update_file>\"")
  179. else:
  180. print("Install the Update Jumper and \"update <update_file>\"")
  181. sys.exit(1)
  182. return usb
  183. # Local variables:
  184. # python-indent: 4
  185. # End: