util.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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, re, platform
  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. argparse.RawDescriptionHelpFormatter):
  17. def _get_help_string(self, action):
  18. help = action.help
  19. if '%no_default' in help:
  20. return help.replace('%no_default', '')
  21. if ('%(default)' in help
  22. or action.default is None
  23. or action.default is False
  24. or action.default is argparse.SUPPRESS):
  25. return help
  26. return help + ' (default: %(default)s)'
  27. class ArgumentParser(argparse.ArgumentParser):
  28. def __init__(self, formatter_class=CmdlineHelpFormatter, *args, **kwargs):
  29. return super().__init__(formatter_class=formatter_class,
  30. *args, **kwargs)
  31. def drive_letter(letter):
  32. types = {
  33. 'A': (USB.BusType.IBMPC, 0),
  34. 'B': (USB.BusType.IBMPC, 1),
  35. '0': (USB.BusType.Shugart, 0),
  36. '1': (USB.BusType.Shugart, 1),
  37. '2': (USB.BusType.Shugart, 2)
  38. }
  39. if not letter.upper() in types:
  40. raise argparse.ArgumentTypeError("invalid drive letter: '%s'" % letter)
  41. return types[letter.upper()]
  42. def range_str(l):
  43. if len(l) == 0:
  44. return '<none>'
  45. p, str = None, ''
  46. for i in l:
  47. if p is not None and i == p[1]+1:
  48. p = p[0], i
  49. continue
  50. if p is not None:
  51. str += ('%d,' % p[0]) if p[0] == p[1] else ('%d-%d,' % p)
  52. p = (i,i)
  53. if p is not None:
  54. str += ('%d' % p[0]) if p[0] == p[1] else ('%d-%d' % p)
  55. return str
  56. class TrackSet:
  57. class TrackIter:
  58. """Iterate over a TrackSet in physical <cyl,head> order."""
  59. def __init__(self, ts):
  60. l = []
  61. for c in ts.cyls:
  62. for h in ts.heads:
  63. pc = c*ts.step + ts.h_off[h]
  64. l.append((pc, h, c))
  65. l.sort()
  66. self.l = iter(l)
  67. def __next__(self):
  68. self.physical_cyl, self.head, self.cyl = next(self.l)
  69. return self
  70. def __init__(self, trackspec):
  71. self.cyls = list()
  72. self.heads = list()
  73. self.h_off = [0]*2
  74. self.step = 1
  75. self.trackspec = ''
  76. self.update_from_trackspec(trackspec)
  77. def update_from_trackspec(self, trackspec):
  78. """Update a TrackSet based on a trackspec."""
  79. self.trackspec += trackspec
  80. for x in trackspec.split(':'):
  81. k,v = x.split('=')
  82. if k == 'c':
  83. cyls = [False]*100
  84. for crange in v.split(','):
  85. m = re.match('(\d\d?)(-(\d\d?))?$', crange)
  86. if m is None: raise ValueError()
  87. if m.group(3) is None:
  88. s,e = int(m.group(1)), int(m.group(1))
  89. else:
  90. s,e = int(m.group(1)), int(m.group(3))
  91. for c in range(s, e+1):
  92. cyls[c] = True
  93. self.cyls = []
  94. for c in range(len(cyls)):
  95. if cyls[c]: self.cyls.append(c)
  96. elif k == 'h':
  97. heads = [False]*2
  98. for hrange in v.split(','):
  99. m = re.match('([01])(-([01]))?$', hrange)
  100. if m is None: raise ValueError()
  101. if m.group(3) is None:
  102. s,e = int(m.group(1)), int(m.group(1))
  103. else:
  104. s,e = int(m.group(1)), int(m.group(3))
  105. for h in range(s, e+1):
  106. heads[h] = True
  107. self.heads = []
  108. for h in range(len(heads)):
  109. if heads[h]: self.heads.append(h)
  110. elif re.match('h[01].off$', k):
  111. h = int(re.match('h([01]).off$', k).group(1))
  112. m = re.match('([+-][\d])$', v)
  113. if m is None: raise ValueError()
  114. self.h_off[h] = int(m.group(1))
  115. elif k == 'step':
  116. self.step = int(v)
  117. if self.step <= 0: raise ValueError()
  118. else:
  119. raise ValueError()
  120. def __str__(self):
  121. s = 'c=%s' % range_str(self.cyls)
  122. s += ':h=%s' % range_str(self.heads)
  123. for i in range(len(self.h_off)):
  124. x = self.h_off[i]
  125. if x != 0:
  126. s += ':h%d.off=%s%d' % (i, '+' if x >= 0 else '', x)
  127. if self.step != 1: s += ':step=%d' % self.step
  128. return s
  129. def __iter__(self):
  130. return self.TrackIter(self)
  131. def split_opts(seq):
  132. """Splits a name from its list of options."""
  133. parts = seq.split('::')
  134. name, opts = parts[0], dict()
  135. for x in map(lambda x: x.split(':'), parts[1:]):
  136. for y in x:
  137. try:
  138. opt, val = y.split('=')
  139. except ValueError:
  140. opt, val = y, True
  141. if opt:
  142. opts[opt] = val
  143. return name, opts
  144. def get_image_class(name):
  145. image_types = { '.adf': 'ADF',
  146. '.d81': 'D81',
  147. '.dsd': 'DSD',
  148. '.dsk': 'EDSK',
  149. '.hfe': 'HFE',
  150. '.ima': 'IMG',
  151. '.img': 'IMG',
  152. '.ipf': 'IPF',
  153. '.raw': 'KryoFlux',
  154. '.scp': 'SCP',
  155. '.ssd': 'SSD',
  156. '.st' : 'IMG' }
  157. if os.path.isdir(name):
  158. typename = 'KryoFlux'
  159. else:
  160. _, ext = os.path.splitext(name)
  161. error.check(ext.lower() in image_types,
  162. """\
  163. %s: Unrecognised file suffix '%s'
  164. Known suffixes: %s"""
  165. % (name, ext, ', '.join(image_types)))
  166. typename = image_types[ext.lower()]
  167. mod = importlib.import_module('greaseweazle.image.' + typename.lower())
  168. return mod.__dict__[typename]
  169. def with_drive_selected(fn, usb, args, *_args, **_kwargs):
  170. usb.set_bus_type(args.drive[0])
  171. try:
  172. usb.drive_select(args.drive[1])
  173. usb.drive_motor(args.drive[1], _kwargs.pop('motor', True))
  174. fn(usb, args, *_args, **_kwargs)
  175. except KeyboardInterrupt:
  176. print()
  177. usb.reset()
  178. raise
  179. finally:
  180. usb.drive_motor(args.drive[1], False)
  181. usb.drive_deselect()
  182. def valid_ser_id(ser_id):
  183. return ser_id and ser_id.upper().startswith("GW")
  184. def score_port(x, old_port=None):
  185. score = 0
  186. if x.manufacturer == "Keir Fraser" and x.product == "Greaseweazle":
  187. score = 20
  188. elif x.vid == 0x1209 and x.pid == 0x4d69:
  189. # Our very own properly-assigned PID. Guaranteed to be us.
  190. score = 20
  191. elif x.vid == 0x1209 and x.pid == 0x0001:
  192. # Our old shared Test PID. It's not guaranteed to be us.
  193. score = 10
  194. if score > 0 and valid_ser_id(x.serial_number):
  195. # A valid serial id is a good sign unless this is a reopen, and
  196. # the serials don't match!
  197. if not old_port or not valid_ser_id(old_port.serial_number):
  198. score = 20
  199. elif x.serial_number == old_port.serial_number:
  200. score = 30
  201. else:
  202. score = 0
  203. if old_port and old_port.location:
  204. # If this is a reopen, location field must match. A match is not
  205. # sufficient in itself however, as Windows may supply the same
  206. # location for multiple USB ports (this may be an interaction with
  207. # BitDefender). Hence we do not increase the port's score here.
  208. if not x.location or x.location != old_port.location:
  209. score = 0
  210. return score
  211. def find_port(old_port=None):
  212. best_score, best_port = 0, None
  213. for x in serial.tools.list_ports.comports():
  214. score = score_port(x, old_port)
  215. if score > best_score:
  216. best_score, best_port = score, x
  217. if best_port:
  218. return best_port.device
  219. raise serial.SerialException('Cannot find the Greaseweazle device')
  220. def port_info(devname):
  221. for x in serial.tools.list_ports.comports():
  222. if x.device == devname:
  223. return x
  224. return None
  225. def usb_reopen(usb, is_update):
  226. mode = { False: 1, True: 0 }
  227. try:
  228. usb.switch_fw_mode(mode[is_update])
  229. except (serial.SerialException, struct.error):
  230. # Mac and Linux raise SerialException ("... returned no data")
  231. # Win10 pyserial returns a short read which fails struct.unpack
  232. pass
  233. usb.ser.close()
  234. for i in range(10):
  235. time.sleep(0.5)
  236. try:
  237. devicename = find_port(usb.port_info)
  238. new_ser = serial.Serial(devicename)
  239. except serial.SerialException:
  240. # Device not found
  241. pass
  242. else:
  243. new_usb = USB.Unit(new_ser)
  244. new_usb.port_info = port_info(devicename)
  245. new_usb.jumperless_update = usb.jumperless_update
  246. return new_usb
  247. raise serial.SerialException('Could not reopen port after mode switch')
  248. def print_update_instructions(usb):
  249. print("To perform an Update:")
  250. if not usb.jumperless_update:
  251. print(" - Disconnect from USB")
  252. print(" - Install the Update Jumper at pins %s"
  253. % ("RXI-TXO" if usb.hw_model != 1 else "DCLK-GND"))
  254. print(" - Reconnect to USB")
  255. print(" - Run \"gw update\" to install firmware v%u.%u" %
  256. (version.major, version.minor))
  257. def usb_open(devicename, is_update=False, mode_check=True):
  258. if devicename is None:
  259. devicename = find_port()
  260. usb = USB.Unit(serial.Serial(devicename))
  261. usb.port_info = port_info(devicename)
  262. is_win7 = (platform.system() == 'Windows' and platform.release() == '7')
  263. usb.jumperless_update = ((usb.hw_model, usb.hw_submodel) != (1, 0)
  264. and not is_win7)
  265. if not mode_check:
  266. return usb
  267. if usb.update_mode and not is_update:
  268. if usb.jumperless_update and not usb.update_jumpered:
  269. usb = usb_reopen(usb, is_update)
  270. if not usb.update_mode:
  271. return usb
  272. print("ERROR: Greaseweazle is in Firmware Update Mode")
  273. print(" - The only available action is \"gw update\"")
  274. if usb.update_jumpered:
  275. print(" - For normal operation disconnect from USB and remove "
  276. "the Update Jumper at pins %s"
  277. % ("RXI-TXO" if usb.hw_model != 1 else "DCLK-GND"))
  278. else:
  279. print(" - Main firmware is erased: You *must* perform an update!")
  280. sys.exit(1)
  281. if is_update and not usb.update_mode:
  282. if usb.jumperless_update:
  283. usb = usb_reopen(usb, is_update)
  284. error.check(usb.update_mode, """\
  285. Greaseweazle F7 did not change to Firmware Update Mode as requested.
  286. If the problem persists, install the Update Jumper at pins RXI-TXO.""")
  287. return usb
  288. print("ERROR: Greaseweazle is not in Firmware Update Mode")
  289. print_update_instructions(usb)
  290. sys.exit(1)
  291. if not usb.update_mode and usb.update_needed:
  292. print("ERROR: Greaseweazle firmware v%u.%u is unsupported"
  293. % (usb.major, usb.minor))
  294. print_update_instructions(usb)
  295. sys.exit(1)
  296. return usb
  297. # Local variables:
  298. # python-indent: 4
  299. # End: