usb.py 18 KB

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