gw.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. # gw.py
  2. #
  3. # Greaseweazle control script.
  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 crcmod.predefined
  10. import sys, struct, argparse, serial
  11. from timeit import default_timer as timer
  12. from greaseweazle import version, USB
  13. # 40MHz
  14. scp_freq = 40000000
  15. # flux_to_scp:
  16. # Converts Greaseweazle flux samples into a Supercard Pro Track.
  17. # Returns the Track Data Header (TDH) and the SCP "bitcell" array.
  18. def flux_to_scp(flux, index_times, track, nr_revs):
  19. factor = scp_freq / usb.sample_freq
  20. tdh = struct.pack("<3sB", b"TRK", track)
  21. dat = bytearray()
  22. len_at_index = rev = 0
  23. to_index = index_times[0]
  24. rem = 0.0
  25. for x in flux:
  26. # Are we processing initial samples before the first revolution?
  27. if rev == 0:
  28. if to_index >= x:
  29. # Discard initial samples
  30. to_index -= x
  31. continue
  32. # Now starting the first full revolution
  33. rev = 1
  34. to_index += index_times[rev]
  35. # Does the next flux interval cross the index mark?
  36. while to_index < x:
  37. # Append to the Track Data Header for the previous full revolution
  38. tdh += struct.pack("<III",
  39. int(round(index_times[rev]*factor)),
  40. (len(dat) - len_at_index) // 2,
  41. 4 + nr_revs*12 + len_at_index)
  42. # Set up for the next revolution
  43. len_at_index = len(dat)
  44. rev += 1
  45. if rev > nr_revs:
  46. # We're done: We simply discard any surplus flux samples
  47. return tdh, dat
  48. to_index += index_times[rev]
  49. # Process the current flux sample into SCP "bitcell" format
  50. to_index -= x
  51. y = x * factor + rem
  52. val = int(round(y))
  53. if (val & 65535) == 0:
  54. val += 1
  55. rem = y - val
  56. while val >= 65536:
  57. dat.append(0)
  58. dat.append(0)
  59. val -= 65536
  60. dat.append(val>>8)
  61. dat.append(val&255)
  62. # Header for last track(s) in case we ran out of flux timings.
  63. while rev <= nr_revs:
  64. tdh += struct.pack("<III",
  65. int(round(index_times[rev]*factor)),
  66. (len(dat) - len_at_index) // 2,
  67. 4 + nr_revs*12 + len_at_index)
  68. len_at_index = len(dat)
  69. rev += 1
  70. return tdh, dat
  71. # read_to_scp:
  72. # Reads a floppy disk and dumps it into a new Supercard Pro image file.
  73. def read_to_scp(args):
  74. trk_dat = bytearray()
  75. trk_offs = []
  76. if args.single_sided:
  77. track_range = range(args.scyl, args.ecyl+1)
  78. nr_sides = 1
  79. else:
  80. track_range = range(args.scyl*2, (args.ecyl+1)*2)
  81. nr_sides = 2
  82. for track in track_range:
  83. cyl = track >> (nr_sides - 1)
  84. side = track & (nr_sides - 1)
  85. print("\rReading Track %u.%u..." % (cyl, side), end="")
  86. trk_offs.append(len(trk_dat))
  87. usb.seek(cyl, side)
  88. for retry in range(1, 5):
  89. ack, index_times, enc_flux = usb.read_track(args.revs+1)
  90. if ack == USB.Ack.Okay:
  91. break
  92. elif ack == USB.Ack.FluxOverflow and retry < 5:
  93. print("Retry #%u..." % (retry))
  94. else:
  95. raise CmdError(ack)
  96. flux = usb.decode_flux(enc_flux)
  97. tdh, dat = flux_to_scp(flux, index_times, track, args.revs)
  98. trk_dat += tdh
  99. trk_dat += dat
  100. print()
  101. csum = 0
  102. for x in trk_dat:
  103. csum += x
  104. trk_offs_dat = bytearray()
  105. for x in trk_offs:
  106. trk_offs_dat += struct.pack("<I", 0x2b0 + x)
  107. trk_offs_dat += bytes(0x2a0 - len(trk_offs_dat))
  108. for x in trk_offs_dat:
  109. csum += x
  110. ds_flag = 0
  111. if args.single_sided:
  112. ds_flag = 1
  113. header_dat = struct.pack("<3s9BI",
  114. b"SCP", # Signature
  115. 0, # Version
  116. 0x80, # DiskType = Other
  117. args.revs, # Nr Revolutions
  118. track_range.start, # Start track
  119. track_range.stop-1, # End track
  120. 0x01, # Flags = Index
  121. 0, # 16-bit cell width
  122. ds_flag, # Double Sided
  123. 0, # 25ns capture
  124. csum & 0xffffffff)
  125. with open(args.file, "wb") as f:
  126. f.write(header_dat)
  127. f.write(trk_offs_dat)
  128. f.write(trk_dat)
  129. # write_from_scp:
  130. # Writes the specified Supercard Pro image file to floppy disk.
  131. def write_from_scp(args):
  132. if args.adjust_speed:
  133. # @drive_ticks is the time in Gresaeweazle ticks between index pulses.
  134. # We will adjust the flux intervals per track to allow for this.
  135. for retry in range(1, 5):
  136. ack, index_times, _ = usb.read_track(3)
  137. if ack == USB.Ack.Okay:
  138. break
  139. elif ack != USB.Ack.FluxOverflow or retry >= 5:
  140. raise CmdError(ack)
  141. drive_ticks = (index_times[1] + index_times[2]) / 2
  142. else:
  143. # Simple ratio between the Greaseweazle and SCP sample frequencies.
  144. factor = usb.sample_freq / scp_freq
  145. # Parse the SCP image header.
  146. with open(args.file, "rb") as f:
  147. dat = f.read()
  148. header = struct.unpack("<3s9BI", dat[0:16])
  149. assert header[0] == b"SCP"
  150. trk_offs = struct.unpack("<168I", dat[16:0x2b0])
  151. if args.single_sided:
  152. track_range = range(args.scyl, args.ecyl+1)
  153. nr_sides = 1
  154. else:
  155. track_range = range(args.scyl*2, (args.ecyl+1)*2)
  156. nr_sides = 2
  157. for i in track_range:
  158. cyl = i >> (nr_sides - 1)
  159. side = i & (nr_sides - 1)
  160. print("\rWriting Track %u.%u..." % (cyl, side), end="")
  161. if trk_offs[i] == 0:
  162. continue
  163. usb.seek(cyl, side)
  164. # Parse the SCP track header and extract the flux data.
  165. thdr = struct.unpack("<3sBIII", dat[trk_offs[i]:trk_offs[i]+16])
  166. sig, _, track_ticks, samples,off = thdr
  167. assert sig == b"TRK"
  168. tdat = dat[trk_offs[i]+off:trk_offs[i]+off+samples*2]
  169. # Decode the SCP flux data into a simple list of flux times.
  170. flux = []
  171. rem = 0.0
  172. if args.adjust_speed:
  173. # @factor adjusts flux times for speed variations between the
  174. # read-in and write-out drives.
  175. factor = drive_ticks / track_ticks
  176. for i in range(0,len(tdat),2):
  177. x = tdat[i]*256 + tdat[i+1]
  178. if x == 0:
  179. rem += 65536.0
  180. continue
  181. y = x * factor + rem
  182. val = int(round(y))
  183. rem = y - val
  184. flux.append(val)
  185. # Encode the flux times for Greaseweazle, and write them out.
  186. enc_flux = usb.encode_flux(flux)
  187. for retry in range(1, 5):
  188. ack = usb.write_track(enc_flux)
  189. if ack == USB.Ack.Okay:
  190. break
  191. elif ack == USB.Ack.FluxUnderflow and retry < 5:
  192. print("Retry #%u..." % (retry))
  193. else:
  194. raise CmdError(ack)
  195. print()
  196. # update_firmware:
  197. # Updates the Greaseweazle firmware using the specified Update File.
  198. def update_firmware(args):
  199. # Check that an update operation was actually requested.
  200. if args.action != "update":
  201. print("Greaseweazle is in Firmware Update Mode:")
  202. print(" The only available action is \"update <update_file>\"")
  203. if usb.update_jumpered:
  204. print(" Remove the Update Jumper for normal operation")
  205. else:
  206. print(" Main firmware is erased: You *must* perform an update!")
  207. return
  208. # Check that the firmware is actually in update mode.
  209. if not usb.update_mode:
  210. print("Greaseweazle is in Normal Mode:")
  211. print(" To \"update\" you must install the Update Jumper")
  212. return
  213. # Read and check the update file.
  214. with open(args.file, "rb") as f:
  215. dat = f.read()
  216. sig, maj, min, pad1, pad2, crc = struct.unpack(">2s4BH", dat[-8:])
  217. if len(dat) & 3 != 0 or sig != b'GW' or pad1 != 0 or pad2 != 0:
  218. print("%s: Bad update file" % (args.file))
  219. return
  220. crc16 = crcmod.predefined.Crc('crc-ccitt-false')
  221. crc16.update(dat)
  222. if crc16.crcValue != 0:
  223. print("%s: Bad CRC" % (args.file))
  224. # Perform the update.
  225. print("Updating to v%u.%u..." % (maj, min))
  226. ack = usb.update_firmware(dat)
  227. if ack != 0:
  228. print("** UPDATE FAILED: Please retry!")
  229. return
  230. print("Done.")
  231. print("** Disconnect Greaseweazle and remove the Programming Jumper.")
  232. # _main:
  233. # Argument processing and dispatch.
  234. def _main(argv):
  235. actions = {
  236. "read" : read_to_scp,
  237. "write" : write_from_scp,
  238. "update" : update_firmware
  239. }
  240. parser = argparse.ArgumentParser(
  241. formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  242. parser.add_argument("action")
  243. parser.add_argument("--revs", type=int, default=3,
  244. help="number of revolutions to read per track")
  245. parser.add_argument("--scyl", type=int, default=0,
  246. help="first cylinder to read/write")
  247. parser.add_argument("--ecyl", type=int, default=81,
  248. help="last cylinder to read/write")
  249. parser.add_argument("--single-sided", action="store_true",
  250. help="read/write a single-sided image")
  251. parser.add_argument("--adjust-speed", action="store_true",
  252. help="adjust write-flux times for drive speed")
  253. parser.add_argument("file", help="in/out filename")
  254. parser.add_argument("device", help="serial device")
  255. args = parser.parse_args(argv[1:])
  256. if not args.action in actions:
  257. print("** Action \"%s\" is not recognised" % args.action)
  258. print("Valid actions: ", end="")
  259. print(", ".join(str(key) for key in actions.keys()))
  260. return
  261. global usb
  262. usb = USB.Unit(serial.Serial(args.device))
  263. print("** %s v%u.%u, Host Tools v%u.%u"
  264. % (("Greaseweazle","Bootloader")[usb.update_mode],
  265. usb.major, usb.minor,
  266. version.major, version.minor))
  267. if args.action == "update" or usb.update_mode:
  268. return actions[args.action](args)
  269. elif usb.update_needed:
  270. print("Firmware is out of date: Require v%u.%u"
  271. % (version.major, version.minor))
  272. print("Install the Update Jumper and \"update <update_file>\"")
  273. return
  274. #usb.step_delay = 5000
  275. #print("Select Delay: %uus" % usb.select_delay)
  276. #print("Step Delay: %uus" % usb.step_delay)
  277. #print("Settle Time: %ums" % usb.seek_settle_delay)
  278. #print("Motor Delay: %ums" % usb.motor_delay)
  279. #print("Auto Off: %ums" % usb.auto_off_delay)
  280. try:
  281. usb.drive_select(True)
  282. usb.drive_motor(True)
  283. actions[args.action](args)
  284. except KeyboardInterrupt:
  285. print()
  286. usb.reset()
  287. usb.ser.close()
  288. usb.ser.open()
  289. finally:
  290. usb.drive_motor(False)
  291. usb.drive_select(False)
  292. def main(argv):
  293. try:
  294. _main(argv)
  295. except USB.CmdError as error:
  296. print("Command Failed: %s" % error)
  297. if __name__ == "__main__":
  298. main(sys.argv)
  299. # Local variables:
  300. # python-indent: 4
  301. # End: