usb.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. # greaseweazle/usb.py
  2. #
  3. # Written & released by Keir Fraser <keir.xen@gmail.com>
  4. #
  5. # This is free and unencumbered software released into the public domain.
  6. # See the file COPYING for more details, or visit <http://unlicense.org>.
  7. import struct
  8. import itertools as it
  9. from greaseweazle import version
  10. from greaseweazle import error
  11. from greaseweazle.flux import Flux
  12. from greaseweazle import optimised
  13. EARLIEST_SUPPORTED_FIRMWARE = (0, 23)
  14. ## Control-Path command set
  15. class ControlCmd:
  16. ClearComms = 10000
  17. Normal = 9600
  18. ## Command set
  19. class Cmd:
  20. GetInfo = 0
  21. Update = 1
  22. Seek = 2
  23. Head = 3
  24. SetParams = 4
  25. GetParams = 5
  26. Motor = 6
  27. ReadFlux = 7
  28. WriteFlux = 8
  29. GetFluxStatus = 9
  30. GetIndexTimes = 10
  31. SwitchFwMode = 11
  32. Select = 12
  33. Deselect = 13
  34. SetBusType = 14
  35. SetPin = 15
  36. Reset = 16
  37. EraseFlux = 17
  38. SourceBytes = 18
  39. SinkBytes = 19
  40. str = {
  41. GetInfo: "GetInfo",
  42. Update: "Update",
  43. Seek: "Seek",
  44. Head: "Head",
  45. SetParams: "SetParams",
  46. GetParams: "GetParams",
  47. Motor: "Motor",
  48. ReadFlux: "ReadFlux",
  49. WriteFlux: "WriteFlux",
  50. GetFluxStatus: "GetFluxStatus",
  51. GetIndexTimes: "GetIndexTimes",
  52. SwitchFwMode: "SwitchFwMode",
  53. Select: "Select",
  54. Deselect: "Deselect",
  55. SetBusType: "SetBusType",
  56. SetPin: "SetPin",
  57. Reset: "Reset",
  58. EraseFlux: "EraseFlux",
  59. SourceBytes: "SourceBytes",
  60. SinkBytes: "SinkBytes"
  61. }
  62. ## Command responses/acknowledgements
  63. class Ack:
  64. Okay = 0
  65. BadCommand = 1
  66. NoIndex = 2
  67. NoTrk0 = 3
  68. FluxOverflow = 4
  69. FluxUnderflow = 5
  70. Wrprot = 6
  71. NoUnit = 7
  72. NoBus = 8
  73. BadUnit = 9
  74. BadPin = 10
  75. BadCylinder = 11
  76. str = {
  77. Okay: "Okay",
  78. BadCommand: "Bad Command",
  79. NoIndex: "No Index",
  80. NoTrk0: "Track 0 not found",
  81. FluxOverflow: "Flux Overflow",
  82. FluxUnderflow: "Flux Underflow",
  83. Wrprot: "Disk is Write Protected",
  84. NoUnit: "No drive unit selected",
  85. NoBus: "No bus type (eg. Shugart, IBM/PC) specified",
  86. BadUnit: "Invalid unit number",
  87. BadPin: "Not a modifiable pin",
  88. BadCylinder: "Invalid cylinder"
  89. }
  90. ## Cmd.GetInfo indexes
  91. class GetInfo:
  92. Firmware = 0
  93. BandwidthStats = 1
  94. ## Cmd.{Get,Set}Params indexes
  95. class Params:
  96. Delays = 0
  97. ## Cmd.SetBusType values
  98. class BusType:
  99. Invalid = 0
  100. IBMPC = 1
  101. Shugart = 2
  102. ## Flux read stream opcodes, preceded by 0xFF byte
  103. class FluxOp:
  104. Index = 1
  105. Space = 2
  106. Astable = 3
  107. ## CmdError: Encapsulates a command acknowledgement.
  108. class CmdError(Exception):
  109. def __init__(self, cmd, code):
  110. self.cmd = cmd
  111. self.code = code
  112. def cmd_str(self):
  113. return Cmd.str.get(self.cmd[0], "UnknownCmd")
  114. def errcode_str(self):
  115. if self.code == Ack.BadCylinder:
  116. s = Ack.str[Ack.BadCylinder]
  117. return s + " %d" % struct.unpack('2Bb', self.cmd)[2]
  118. return Ack.str.get(self.code, "Unknown Error (%u)" % self.code)
  119. def __str__(self):
  120. return "%s: %s" % (self.cmd_str(), self.errcode_str())
  121. class Unit:
  122. ## Unit information, instance variables:
  123. ## major, minor: Greaseweazle firmware version number
  124. ## max_cmd: Maximum Cmd number accepted by this unit
  125. ## sample_freq: Resolution of all time values passed to/from this unit
  126. ## update_mode: True iff the Greaseweazle unit is in update mode
  127. ## Unit(ser):
  128. ## Accepts a Pyserial instance for Greaseweazle communications.
  129. def __init__(self, ser):
  130. self.ser = ser
  131. self.reset()
  132. # Copy firmware info to instance variables (see above for definitions).
  133. self._send_cmd(struct.pack("3B", Cmd.GetInfo, 3, GetInfo.Firmware))
  134. x = struct.unpack("<4BI3B21x", self.ser.read(32))
  135. (self.major, self.minor, is_main_firmware,
  136. self.max_cmd, self.sample_freq, self.hw_model,
  137. self.hw_submodel, self.usb_speed) = x
  138. self.version = (self.major, self.minor)
  139. # Old firmware doesn't report HW type but runs on STM32F1 only.
  140. if self.hw_model == 0:
  141. self.hw_model = 1
  142. # Check whether firmware is in update mode: limited command set if so.
  143. self.update_mode = (is_main_firmware == 0)
  144. if self.update_mode:
  145. self.update_jumpered = (self.sample_freq & 1)
  146. del self.sample_freq
  147. return
  148. # We are running main firmware: Check whether an update is needed.
  149. # We can use only the GetInfo command if the firmware is out of date.
  150. self.update_needed = (self.version < EARLIEST_SUPPORTED_FIRMWARE or
  151. self.version > (version.major, version.minor))
  152. if self.update_needed:
  153. return
  154. # Initialise the delay properties with current firmware values.
  155. self._send_cmd(struct.pack("4B", Cmd.GetParams, 4, Params.Delays, 10))
  156. (self._select_delay, self._step_delay,
  157. self._seek_settle_delay, self._motor_delay,
  158. self._auto_off_delay) = struct.unpack("<5H", self.ser.read(10))
  159. ## reset:
  160. ## Resets communications with Greaseweazle.
  161. def reset(self):
  162. self.ser.reset_output_buffer()
  163. self.ser.baudrate = ControlCmd.ClearComms
  164. self.ser.baudrate = ControlCmd.Normal
  165. self.ser.reset_input_buffer()
  166. ## _send_cmd:
  167. ## Send given command byte sequence to Greaseweazle.
  168. ## Raise a CmdError if command fails.
  169. def _send_cmd(self, cmd):
  170. self.ser.write(cmd)
  171. (c,r) = struct.unpack("2B", self.ser.read(2))
  172. error.check(c == cmd[0], "Command returned garbage (%02x != %02x)"
  173. % (c, cmd[0]))
  174. if r != 0:
  175. raise CmdError(cmd, r)
  176. ## seek:
  177. ## Seek the selected drive's heads to the specified track (cyl, head).
  178. def seek(self, cyl, head):
  179. self._send_cmd(struct.pack("2Bb", Cmd.Seek, 3, cyl))
  180. self._send_cmd(struct.pack("3B", Cmd.Head, 3, head))
  181. ## set_bus_type:
  182. ## Set the floppy bus type.
  183. def set_bus_type(self, type):
  184. self._send_cmd(struct.pack("3B", Cmd.SetBusType, 3, type))
  185. ## set_pin:
  186. ## Set a pin level.
  187. def set_pin(self, pin, level):
  188. self._send_cmd(struct.pack("4B", Cmd.SetPin, 4, pin, int(level)))
  189. ## power_on_reset:
  190. ## Re-initialise to power-on defaults.
  191. def power_on_reset(self):
  192. self._send_cmd(struct.pack("2B", Cmd.Reset, 2))
  193. ## drive_select:
  194. ## Select the specified drive unit.
  195. def drive_select(self, unit):
  196. self._send_cmd(struct.pack("3B", Cmd.Select, 3, unit))
  197. ## drive_deselect:
  198. ## Deselect currently-selected drive unit (if any).
  199. def drive_deselect(self):
  200. self._send_cmd(struct.pack("2B", Cmd.Deselect, 2))
  201. ## drive_motor:
  202. ## Turn the specified drive's motor on/off.
  203. def drive_motor(self, unit, state):
  204. self._send_cmd(struct.pack("4B", Cmd.Motor, 4, unit, int(state)))
  205. ## switch_fw_mode:
  206. ## Switch between update bootloader and main firmware.
  207. def switch_fw_mode(self, mode):
  208. self._send_cmd(struct.pack("3B", Cmd.SwitchFwMode, 3, int(mode)))
  209. ## update_firmware:
  210. ## Update Greaseweazle to the given new firmware.
  211. def update_firmware(self, dat):
  212. self._send_cmd(struct.pack("<2BI", Cmd.Update, 6, len(dat)))
  213. self.ser.write(dat)
  214. (ack,) = struct.unpack("B", self.ser.read(1))
  215. return ack
  216. ## update_bootloader:
  217. ## Update Greaseweazle with the given new bootloader.
  218. def update_bootloader(self, dat):
  219. self._send_cmd(struct.pack("<2B2I", Cmd.Update, 10,
  220. len(dat), 0xdeafbee3))
  221. self.ser.write(dat)
  222. (ack,) = struct.unpack("B", self.ser.read(1))
  223. return ack
  224. ## _decode_flux:
  225. ## Decode the Greaseweazle data stream into a list of flux samples.
  226. def _decode_flux(self, dat):
  227. flux, index = [], []
  228. assert dat[-1] == 0
  229. dat_i = it.islice(dat, 0, len(dat)-1)
  230. ticks, ticks_since_index = 0, 0
  231. def _read_28bit():
  232. val = (next(dat_i) & 254) >> 1
  233. val += (next(dat_i) & 254) << 6
  234. val += (next(dat_i) & 254) << 13
  235. val += (next(dat_i) & 254) << 20
  236. return val
  237. try:
  238. while True:
  239. i = next(dat_i)
  240. if i == 255:
  241. opcode = next(dat_i)
  242. if opcode == FluxOp.Index:
  243. val = _read_28bit()
  244. index.append(ticks_since_index + ticks + val)
  245. ticks_since_index = -(ticks + val)
  246. elif opcode == FluxOp.Space:
  247. ticks += _read_28bit()
  248. else:
  249. raise error.Fatal("Bad opcode in flux stream (%d)"
  250. % opcode)
  251. else:
  252. if i < 250:
  253. val = i
  254. else:
  255. val = 250 + (i - 250) * 255
  256. val += next(dat_i) - 1
  257. ticks += val
  258. flux.append(ticks)
  259. ticks_since_index += ticks
  260. ticks = 0
  261. except StopIteration:
  262. pass
  263. return flux, index
  264. ## _encode_flux:
  265. ## Convert the given flux timings into an encoded data stream.
  266. def _encode_flux(self, flux):
  267. nfa_thresh = round(150e-6 * self.sample_freq) # 150us
  268. nfa_period = round(1.25e-6 * self.sample_freq) # 1.25us
  269. dat = bytearray()
  270. def _write_28bit(x):
  271. dat.append(1 | (x<<1) & 255)
  272. dat.append(1 | (x>>6) & 255)
  273. dat.append(1 | (x>>13) & 255)
  274. dat.append(1 | (x>>20) & 255)
  275. # Emit a dummy final flux value. This is never written to disk because
  276. # the write is aborted immediately the final flux is loaded into the
  277. # WDATA timer. The dummy flux is sacrificial, ensuring that the real
  278. # final flux gets written in full.
  279. dummy_flux = round(100e-6 * self.sample_freq)
  280. for val in it.chain(flux, [dummy_flux]):
  281. if val == 0:
  282. pass
  283. elif val < 250:
  284. dat.append(val)
  285. elif val > nfa_thresh:
  286. dat.append(255)
  287. dat.append(FluxOp.Space)
  288. _write_28bit(val)
  289. dat.append(255)
  290. dat.append(FluxOp.Astable)
  291. _write_28bit(nfa_period)
  292. else:
  293. high = (val-250) // 255
  294. if high < 5:
  295. dat.append(250 + high)
  296. dat.append(1 + (val-250) % 255)
  297. else:
  298. dat.append(255)
  299. dat.append(FluxOp.Space)
  300. _write_28bit(val - 249)
  301. dat.append(249)
  302. dat.append(0) # End of Stream
  303. return dat
  304. ## _read_track:
  305. ## Private helper which issues command requests to Greaseweazle.
  306. def _read_track(self, revs, ticks):
  307. # Request and read all flux timings for this track.
  308. dat = bytearray()
  309. self._send_cmd(struct.pack("<2BIH", Cmd.ReadFlux, 8,
  310. ticks, revs+1))
  311. while True:
  312. dat += self.ser.read(1)
  313. dat += self.ser.read(self.ser.in_waiting)
  314. if dat[-1] == 0:
  315. break
  316. # Check flux status. An exception is raised if there was an error.
  317. self._send_cmd(struct.pack("2B", Cmd.GetFluxStatus, 2))
  318. return dat
  319. ## read_track:
  320. ## Read and decode flux and index timings for the current track.
  321. def read_track(self, revs, ticks=0, nr_retries=5):
  322. retry = 0
  323. while True:
  324. try:
  325. dat = self._read_track(revs, ticks)
  326. except CmdError as error:
  327. # An error occurred. We may retry on transient overflows.
  328. if error.code == Ack.FluxOverflow and retry < nr_retries:
  329. retry += 1
  330. else:
  331. raise error
  332. else:
  333. # Success!
  334. break
  335. try:
  336. # Decode the flux list and read the index-times list.
  337. flux_list, index_list = optimised.decode_flux(dat)
  338. except AttributeError:
  339. flux_list, index_list = self._decode_flux(dat)
  340. # Success: Return the requested full index-to-index revolutions.
  341. return Flux(index_list, flux_list, self.sample_freq, index_cued=False)
  342. ## write_track:
  343. ## Write the given flux stream to the current track via Greaseweazle.
  344. def write_track(self, flux_list, terminate_at_index,
  345. cue_at_index=True, nr_retries=5):
  346. # Create encoded data stream.
  347. dat = self._encode_flux(flux_list)
  348. retry = 0
  349. while True:
  350. try:
  351. # Write the flux stream to the track via Greaseweazle.
  352. self._send_cmd(struct.pack("4B", Cmd.WriteFlux, 4,
  353. int(cue_at_index),
  354. int(terminate_at_index)))
  355. self.ser.write(dat)
  356. self.ser.read(1) # Sync with Greaseweazle
  357. self._send_cmd(struct.pack("2B", Cmd.GetFluxStatus, 2))
  358. except CmdError as error:
  359. # An error occurred. We may retry on transient underflows.
  360. if error.code == Ack.FluxUnderflow and retry < nr_retries:
  361. retry += 1
  362. else:
  363. raise error
  364. else:
  365. # Success!
  366. break
  367. ## erase_track:
  368. ## Erase the current track via Greaseweazle.
  369. def erase_track(self, ticks):
  370. self._send_cmd(struct.pack("<2BI", Cmd.EraseFlux, 6, int(ticks)))
  371. self.ser.read(1) # Sync with Greaseweazle
  372. self._send_cmd(struct.pack("2B", Cmd.GetFluxStatus, 2))
  373. ## source_bytes:
  374. ## Command Greaseweazle to source 'nr' garbage bytes.
  375. def source_bytes(self, nr):
  376. self._send_cmd(struct.pack("<2BI", Cmd.SourceBytes, 6, nr))
  377. while nr > 0:
  378. self.ser.read(1)
  379. waiting = self.ser.in_waiting
  380. self.ser.read(waiting)
  381. nr -= 1 + waiting
  382. ## sink_bytes:
  383. ## Command Greaseweazle to sink 'nr' garbage bytes.
  384. def sink_bytes(self, nr):
  385. self._send_cmd(struct.pack("<2BI", Cmd.SinkBytes, 6, nr))
  386. dat = bytes(1024*1024)
  387. while nr > len(dat):
  388. self.ser.write(dat)
  389. nr -= len(dat)
  390. self.ser.write(dat[:nr])
  391. self.ser.read(1) # Sync with Greaseweazle
  392. ## bw_stats:
  393. ## Get min/max bandwidth for previous source/sink command. Mbps (float).
  394. def bw_stats(self):
  395. self._send_cmd(struct.pack("3B", Cmd.GetInfo, 3,
  396. GetInfo.BandwidthStats))
  397. min_bytes, min_usecs, max_bytes, max_usecs = struct.unpack(
  398. "<4I16x", self.ser.read(32))
  399. min_bw = (8 * min_bytes) / min_usecs
  400. max_bw = (8 * max_bytes) / max_usecs
  401. return min_bw, max_bw
  402. ##
  403. ## Delay-property public getters and setters:
  404. ## select_delay: Delay (usec) after asserting drive select
  405. ## step_delay: Delay (usec) after issuing a head-step command
  406. ## seek_settle_delay: Delay (msec) after completing a head-seek operation
  407. ## motor_delay: Delay (msec) after turning on drive spindle motor
  408. ## auto_off_delay: Timeout (msec) since last command upon which all
  409. ## drives are deselected and spindle motors turned off
  410. ##
  411. def _set_delays(self):
  412. self._send_cmd(struct.pack("<3B5H", Cmd.SetParams,
  413. 3+5*2, Params.Delays,
  414. self._select_delay, self._step_delay,
  415. self._seek_settle_delay,
  416. self._motor_delay, self._auto_off_delay))
  417. @property
  418. def select_delay(self):
  419. return self._select_delay
  420. @select_delay.setter
  421. def select_delay(self, select_delay):
  422. self._select_delay = select_delay
  423. self._set_delays()
  424. @property
  425. def step_delay(self):
  426. return self._step_delay
  427. @step_delay.setter
  428. def step_delay(self, step_delay):
  429. self._step_delay = step_delay
  430. self._set_delays()
  431. @property
  432. def seek_settle_delay(self):
  433. return self._seek_settle_delay
  434. @seek_settle_delay.setter
  435. def seek_settle_delay(self, seek_settle_delay):
  436. self._seek_settle_delay = seek_settle_delay
  437. self._set_delays()
  438. @property
  439. def motor_delay(self):
  440. return self._motor_delay
  441. @motor_delay.setter
  442. def motor_delay(self, motor_delay):
  443. self._motor_delay = motor_delay
  444. self._set_delays()
  445. @property
  446. def auto_off_delay(self):
  447. return self._auto_off_delay
  448. @auto_off_delay.setter
  449. def auto_off_delay(self, auto_off_delay):
  450. self._auto_off_delay = auto_off_delay
  451. self._set_delays()
  452. # Local variables:
  453. # python-indent: 4
  454. # End: