gw.py 11 KB

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