util.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. '.raw': 'KryoFlux' }
  60. if os.path.isdir(name):
  61. typename = 'KryoFlux'
  62. else:
  63. _, ext = os.path.splitext(name)
  64. error.check(ext.lower() in image_types,
  65. "%s: Unrecognised file suffix '%s'" % (name, ext))
  66. typename = image_types[ext.lower()]
  67. mod = importlib.import_module('greaseweazle.image.' + typename.lower())
  68. return mod.__dict__[typename]
  69. def with_drive_selected(fn, usb, args, *_args, **_kwargs):
  70. usb.set_bus_type(args.drive[0])
  71. try:
  72. usb.drive_select(args.drive[1])
  73. usb.drive_motor(args.drive[1], _kwargs.pop('motor', True))
  74. fn(usb, args, *_args, **_kwargs)
  75. except KeyboardInterrupt:
  76. print()
  77. usb.reset()
  78. usb.ser.close()
  79. usb.ser.open()
  80. raise
  81. finally:
  82. usb.drive_motor(args.drive[1], False)
  83. usb.drive_deselect()
  84. def valid_ser_id(ser_id):
  85. return ser_id and ser_id.upper().startswith("GW")
  86. def score_port(x, old_port=None):
  87. score = 0
  88. if x.manufacturer == "Keir Fraser" and x.product == "Greaseweazle":
  89. score = 20
  90. elif x.vid == 0x1209 and x.pid == 0x4d69:
  91. # Our very own properly-assigned PID. Guaranteed to be us.
  92. score = 20
  93. elif x.vid == 0x1209 and x.pid == 0x0001:
  94. # Our old shared Test PID. It's not guaranteed to be us.
  95. score = 10
  96. if score > 0 and valid_ser_id(x.serial_number):
  97. # A valid serial id is a good sign unless this is a reopen, and
  98. # the serials don't match!
  99. if not old_port or not valid_ser_id(old_port.serial_number):
  100. score = 20
  101. elif x.serial_number == old_port.serial_number:
  102. score = 30
  103. else:
  104. score = 0
  105. if old_port and old_port.location:
  106. # If this is a reopen, location field must match. A match is not
  107. # sufficient in itself however, as Windows may supply the same
  108. # location for multiple USB ports (this may be an interaction with
  109. # BitDefender). Hence we do not increase the port's score here.
  110. if not x.location or x.location != old_port.location:
  111. score = 0
  112. return score
  113. def find_port(old_port=None):
  114. best_score, best_port = 0, None
  115. for x in serial.tools.list_ports.comports():
  116. score = score_port(x, old_port)
  117. if score > best_score:
  118. best_score, best_port = score, x
  119. if best_port:
  120. return best_port.device
  121. raise serial.SerialException('Cannot find the Greaseweazle device')
  122. def port_info(devname):
  123. for x in serial.tools.list_ports.comports():
  124. if x.device == devname:
  125. return x
  126. return None
  127. def usb_reopen(usb, is_update):
  128. mode = { False: 1, True: 0 }
  129. try:
  130. usb.switch_fw_mode(mode[is_update])
  131. except (serial.SerialException, struct.error):
  132. # Mac and Linux raise SerialException ("... returned no data")
  133. # Win10 pyserial returns a short read which fails struct.unpack
  134. pass
  135. usb.ser.close()
  136. for i in range(10):
  137. time.sleep(0.5)
  138. try:
  139. devicename = find_port(usb.port_info)
  140. new_ser = serial.Serial(devicename)
  141. except serial.SerialException:
  142. # Device not found
  143. pass
  144. else:
  145. new_usb = USB.Unit(new_ser)
  146. new_usb.port_info = port_info(devicename)
  147. return new_usb
  148. raise serial.SerialException('Could not reopen port after mode switch')
  149. def usb_open(devicename, is_update=False, mode_check=True):
  150. if devicename is None:
  151. devicename = find_port()
  152. usb = USB.Unit(serial.Serial(devicename))
  153. usb.port_info = port_info(devicename)
  154. if not mode_check:
  155. return usb
  156. if usb.update_mode and not is_update:
  157. if usb.hw_model == 7 and not usb.update_jumpered:
  158. usb = usb_reopen(usb, is_update)
  159. if not usb.update_mode:
  160. return usb
  161. print("Greaseweazle is in Firmware Update Mode:")
  162. print(" The only available action is \"update\" of main firmware")
  163. if usb.update_jumpered:
  164. print(" Remove the Update Jumper for normal operation")
  165. else:
  166. print(" Main firmware is erased: You *must* perform an update!")
  167. sys.exit(1)
  168. if is_update and not usb.update_mode:
  169. if usb.hw_model == 7:
  170. usb = usb_reopen(usb, is_update)
  171. error.check(usb.update_mode, """\
  172. Greaseweazle F7 did not change to Firmware Update Mode as requested.
  173. If the problem persists, install the Update Jumper (across RX/TX).""")
  174. return usb
  175. print("Greaseweazle is in Normal Mode:")
  176. print(" To \"update\" you must install the Update Jumper")
  177. sys.exit(1)
  178. if not usb.update_mode and usb.update_needed:
  179. print("Firmware is out of date: Require v%u.%u"
  180. % (version.major, version.minor))
  181. if usb.hw_model == 7:
  182. print("Run \"update <update_file>\"")
  183. else:
  184. print("Install the Update Jumper and \"update <update_file>\"")
  185. sys.exit(1)
  186. return usb
  187. # Local variables:
  188. # python-indent: 4
  189. # End: