util.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. '.dsk': 'EDSK',
  148. '.hfe': 'HFE',
  149. '.ima': 'IMG',
  150. '.img': 'IMG',
  151. '.ipf': 'IPF',
  152. '.raw': 'KryoFlux',
  153. '.scp': 'SCP',
  154. '.st' : 'IMG' }
  155. if os.path.isdir(name):
  156. typename = 'KryoFlux'
  157. else:
  158. _, ext = os.path.splitext(name)
  159. error.check(ext.lower() in image_types,
  160. """\
  161. %s: Unrecognised file suffix '%s'
  162. Known suffixes: %s"""
  163. % (name, ext, ', '.join(image_types)))
  164. typename = image_types[ext.lower()]
  165. mod = importlib.import_module('greaseweazle.image.' + typename.lower())
  166. return mod.__dict__[typename]
  167. def with_drive_selected(fn, usb, args, *_args, **_kwargs):
  168. usb.set_bus_type(args.drive[0])
  169. try:
  170. usb.drive_select(args.drive[1])
  171. usb.drive_motor(args.drive[1], _kwargs.pop('motor', True))
  172. fn(usb, args, *_args, **_kwargs)
  173. except KeyboardInterrupt:
  174. print()
  175. usb.reset()
  176. raise
  177. finally:
  178. usb.drive_motor(args.drive[1], False)
  179. usb.drive_deselect()
  180. def valid_ser_id(ser_id):
  181. return ser_id and ser_id.upper().startswith("GW")
  182. def score_port(x, old_port=None):
  183. score = 0
  184. if x.manufacturer == "Keir Fraser" and x.product == "Greaseweazle":
  185. score = 20
  186. elif x.vid == 0x1209 and x.pid == 0x4d69:
  187. # Our very own properly-assigned PID. Guaranteed to be us.
  188. score = 20
  189. elif x.vid == 0x1209 and x.pid == 0x0001:
  190. # Our old shared Test PID. It's not guaranteed to be us.
  191. score = 10
  192. if score > 0 and valid_ser_id(x.serial_number):
  193. # A valid serial id is a good sign unless this is a reopen, and
  194. # the serials don't match!
  195. if not old_port or not valid_ser_id(old_port.serial_number):
  196. score = 20
  197. elif x.serial_number == old_port.serial_number:
  198. score = 30
  199. else:
  200. score = 0
  201. if old_port and old_port.location:
  202. # If this is a reopen, location field must match. A match is not
  203. # sufficient in itself however, as Windows may supply the same
  204. # location for multiple USB ports (this may be an interaction with
  205. # BitDefender). Hence we do not increase the port's score here.
  206. if not x.location or x.location != old_port.location:
  207. score = 0
  208. return score
  209. def find_port(old_port=None):
  210. best_score, best_port = 0, None
  211. for x in serial.tools.list_ports.comports():
  212. score = score_port(x, old_port)
  213. if score > best_score:
  214. best_score, best_port = score, x
  215. if best_port:
  216. return best_port.device
  217. raise serial.SerialException('Cannot find the Greaseweazle device')
  218. def port_info(devname):
  219. for x in serial.tools.list_ports.comports():
  220. if x.device == devname:
  221. return x
  222. return None
  223. def usb_reopen(usb, is_update):
  224. mode = { False: 1, True: 0 }
  225. try:
  226. usb.switch_fw_mode(mode[is_update])
  227. except (serial.SerialException, struct.error):
  228. # Mac and Linux raise SerialException ("... returned no data")
  229. # Win10 pyserial returns a short read which fails struct.unpack
  230. pass
  231. usb.ser.close()
  232. for i in range(10):
  233. time.sleep(0.5)
  234. try:
  235. devicename = find_port(usb.port_info)
  236. new_ser = serial.Serial(devicename)
  237. except serial.SerialException:
  238. # Device not found
  239. pass
  240. else:
  241. new_usb = USB.Unit(new_ser)
  242. new_usb.port_info = port_info(devicename)
  243. new_usb.jumperless_update = usb.jumperless_update
  244. return new_usb
  245. raise serial.SerialException('Could not reopen port after mode switch')
  246. def print_update_instructions(usb):
  247. print("To perform an Update:")
  248. if not usb.jumperless_update:
  249. print(" - Disconnect from USB")
  250. print(" - Install the Update Jumper at pins %s"
  251. % ("RXI-TXO" if usb.hw_model != 1 else "DCLK-GND"))
  252. print(" - Reconnect to USB")
  253. print(" - Run \"gw update\" to install firmware v%u.%u" %
  254. (version.major, version.minor))
  255. def usb_open(devicename, is_update=False, mode_check=True):
  256. if devicename is None:
  257. devicename = find_port()
  258. usb = USB.Unit(serial.Serial(devicename))
  259. usb.port_info = port_info(devicename)
  260. is_win7 = (platform.system() == 'Windows' and platform.release() == '7')
  261. usb.jumperless_update = ((usb.hw_model, usb.hw_submodel) != (1, 0)
  262. and not is_win7)
  263. if not mode_check:
  264. return usb
  265. if usb.update_mode and not is_update:
  266. if usb.jumperless_update and not usb.update_jumpered:
  267. usb = usb_reopen(usb, is_update)
  268. if not usb.update_mode:
  269. return usb
  270. print("ERROR: Greaseweazle is in Firmware Update Mode")
  271. print(" - The only available action is \"gw update\"")
  272. if usb.update_jumpered:
  273. print(" - For normal operation disconnect from USB and remove "
  274. "the Update Jumper at pins %s"
  275. % ("RXI-TXO" if usb.hw_model != 1 else "DCLK-GND"))
  276. else:
  277. print(" - Main firmware is erased: You *must* perform an update!")
  278. sys.exit(1)
  279. if is_update and not usb.update_mode:
  280. if usb.jumperless_update:
  281. usb = usb_reopen(usb, is_update)
  282. error.check(usb.update_mode, """\
  283. Greaseweazle F7 did not change to Firmware Update Mode as requested.
  284. If the problem persists, install the Update Jumper at pins RXI-TXO.""")
  285. return usb
  286. print("ERROR: Greaseweazle is not in Firmware Update Mode")
  287. print_update_instructions(usb)
  288. sys.exit(1)
  289. if not usb.update_mode and usb.update_needed:
  290. print("ERROR: Greaseweazle firmware v%u.%u is unsupported"
  291. % (usb.major, usb.minor))
  292. print_update_instructions(usb)
  293. sys.exit(1)
  294. return usb
  295. # Local variables:
  296. # python-indent: 4
  297. # End: