usb.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  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: "Not a modifiable 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. ## power_on_reset:
  196. ## Re-initialise to power-on defaults.
  197. def power_on_reset(self):
  198. self._send_cmd(struct.pack("2B", Cmd.Reset, 2))
  199. ## drive_select:
  200. ## Select the specified drive unit.
  201. def drive_select(self, unit):
  202. self._send_cmd(struct.pack("3B", Cmd.Select, 3, unit))
  203. ## drive_deselect:
  204. ## Deselect currently-selected drive unit (if any).
  205. def drive_deselect(self):
  206. self._send_cmd(struct.pack("2B", Cmd.Deselect, 2))
  207. ## drive_motor:
  208. ## Turn the specified drive's motor on/off.
  209. def drive_motor(self, unit, state):
  210. self._send_cmd(struct.pack("4B", Cmd.Motor, 4, unit, int(state)))
  211. ## switch_fw_mode:
  212. ## Switch between update bootloader and main firmware.
  213. def switch_fw_mode(self, mode):
  214. self._send_cmd(struct.pack("3B", Cmd.SwitchFwMode, 3, int(mode)))
  215. ## update_firmware:
  216. ## Update Greaseweazle to the given new firmware.
  217. def update_firmware(self, dat):
  218. self._send_cmd(struct.pack("<2BI", Cmd.Update, 6, len(dat)))
  219. self.ser.write(dat)
  220. (ack,) = struct.unpack("B", self.ser.read(1))
  221. return ack
  222. ## update_bootloader:
  223. ## Update Greaseweazle with the given new bootloader.
  224. def update_bootloader(self, dat):
  225. self._send_cmd(struct.pack("<2B2I", Cmd.Update, 10,
  226. len(dat), 0xdeafbee3))
  227. self.ser.write(dat)
  228. (ack,) = struct.unpack("B", self.ser.read(1))
  229. return ack
  230. ## _decode_flux:
  231. ## Decode the Greaseweazle data stream into a list of flux samples.
  232. def _decode_flux(self, dat):
  233. flux, index = [], []
  234. assert dat[-1] == 0
  235. dat_i = it.islice(dat, 0, len(dat)-1)
  236. ticks, ticks_since_index = 0, 0
  237. def _read_28bit():
  238. val = (next(dat_i) & 254) >> 1
  239. val += (next(dat_i) & 254) << 6
  240. val += (next(dat_i) & 254) << 13
  241. val += (next(dat_i) & 254) << 20
  242. return val
  243. try:
  244. while True:
  245. i = next(dat_i)
  246. if i == 255:
  247. opcode = next(dat_i)
  248. if opcode == FluxOp.Index:
  249. val = _read_28bit()
  250. index.append(ticks_since_index + ticks + val)
  251. ticks_since_index = -(ticks + val)
  252. elif opcode == FluxOp.Space:
  253. ticks += _read_28bit()
  254. else:
  255. raise error.Fatal("Bad opcode in flux stream (%d)"
  256. % opcode)
  257. else:
  258. if i < 250:
  259. val = i
  260. else:
  261. val = 250 + (i - 250) * 255
  262. val += next(dat_i) - 1
  263. ticks += val
  264. flux.append(ticks)
  265. ticks_since_index += ticks
  266. ticks = 0
  267. except StopIteration:
  268. pass
  269. return flux, index
  270. ## _encode_flux:
  271. ## Convert the given flux timings into an encoded data stream.
  272. def _encode_flux(self, flux):
  273. nfa_thresh = round(150e-6 * self.sample_freq) # 150us
  274. nfa_period = round(1.25e-6 * self.sample_freq) # 1.25us
  275. dat = bytearray()
  276. def _write_28bit(x):
  277. dat.append(1 | (x<<1) & 255)
  278. dat.append(1 | (x>>6) & 255)
  279. dat.append(1 | (x>>13) & 255)
  280. dat.append(1 | (x>>20) & 255)
  281. # Emit a dummy final flux value. This is never written to disk because
  282. # the write is aborted immediately the final flux is loaded into the
  283. # WDATA timer. The dummy flux is sacrificial, ensuring that the real
  284. # final flux gets written in full.
  285. dummy_flux = round(100e-6 * self.sample_freq)
  286. for val in it.chain(flux, [dummy_flux]):
  287. if val == 0:
  288. pass
  289. elif val < 250:
  290. dat.append(val)
  291. elif val > nfa_thresh:
  292. dat.append(255)
  293. dat.append(FluxOp.Space)
  294. _write_28bit(val)
  295. dat.append(255)
  296. dat.append(FluxOp.Astable)
  297. _write_28bit(nfa_period)
  298. else:
  299. high = (val-250) // 255
  300. if high < 5:
  301. dat.append(250 + high)
  302. dat.append(1 + (val-250) % 255)
  303. else:
  304. dat.append(255)
  305. dat.append(FluxOp.Space)
  306. _write_28bit(val - 249)
  307. dat.append(249)
  308. dat.append(0) # End of Stream
  309. return dat
  310. ## _read_track:
  311. ## Private helper which issues command requests to Greaseweazle.
  312. def _read_track(self, revs, ticks):
  313. # Request and read all flux timings for this track.
  314. dat = bytearray()
  315. self._send_cmd(struct.pack("<2BIH", Cmd.ReadFlux, 8,
  316. ticks, revs+1))
  317. while True:
  318. dat += self.ser.read(1)
  319. dat += self.ser.read(self.ser.in_waiting)
  320. if dat[-1] == 0:
  321. break
  322. # Check flux status. An exception is raised if there was an error.
  323. self._send_cmd(struct.pack("2B", Cmd.GetFluxStatus, 2))
  324. return dat
  325. ## read_track:
  326. ## Read and decode flux and index timings for the current track.
  327. def read_track(self, revs, ticks=0, nr_retries=5):
  328. retry = 0
  329. while True:
  330. try:
  331. dat = self._read_track(revs, ticks)
  332. except CmdError as error:
  333. # An error occurred. We may retry on transient overflows.
  334. if error.code == Ack.FluxOverflow and retry < nr_retries:
  335. retry += 1
  336. else:
  337. raise error
  338. else:
  339. # Success!
  340. break
  341. try:
  342. # Decode the flux list and read the index-times list.
  343. flux_list, index_list = optimised.decode_flux(dat)
  344. except AttributeError:
  345. flux_list, index_list = self._decode_flux(dat)
  346. # Success: Return the requested full index-to-index revolutions.
  347. return Flux(index_list, flux_list, self.sample_freq, index_cued=False)
  348. ## write_track:
  349. ## Write the given flux stream to the current track via Greaseweazle.
  350. def write_track(self, flux_list, terminate_at_index,
  351. cue_at_index=True, nr_retries=5):
  352. # Create encoded data stream.
  353. dat = self._encode_flux(flux_list)
  354. retry = 0
  355. while True:
  356. try:
  357. # Write the flux stream to the track via Greaseweazle.
  358. self._send_cmd(struct.pack("4B", Cmd.WriteFlux, 4,
  359. int(cue_at_index),
  360. int(terminate_at_index)))
  361. self.ser.write(dat)
  362. self.ser.read(1) # Sync with Greaseweazle
  363. self._send_cmd(struct.pack("2B", Cmd.GetFluxStatus, 2))
  364. except CmdError as error:
  365. # An error occurred. We may retry on transient underflows.
  366. if error.code == Ack.FluxUnderflow and retry < nr_retries:
  367. retry += 1
  368. else:
  369. raise error
  370. else:
  371. # Success!
  372. break
  373. ## erase_track:
  374. ## Erase the current track via Greaseweazle.
  375. def erase_track(self, ticks):
  376. self._send_cmd(struct.pack("<2BI", Cmd.EraseFlux, 6, int(ticks)))
  377. self.ser.read(1) # Sync with Greaseweazle
  378. self._send_cmd(struct.pack("2B", Cmd.GetFluxStatus, 2))
  379. ## source_bytes:
  380. ## Command Greaseweazle to source 'nr' garbage bytes.
  381. def source_bytes(self, nr):
  382. self._send_cmd(struct.pack("<2BI", Cmd.SourceBytes, 6, nr))
  383. while nr > 0:
  384. self.ser.read(1)
  385. waiting = self.ser.in_waiting
  386. self.ser.read(waiting)
  387. nr -= 1 + waiting
  388. ## sink_bytes:
  389. ## Command Greaseweazle to sink 'nr' garbage bytes.
  390. def sink_bytes(self, nr):
  391. self._send_cmd(struct.pack("<2BI", Cmd.SinkBytes, 6, nr))
  392. dat = bytes(1024*1024)
  393. while nr > len(dat):
  394. self.ser.write(dat)
  395. nr -= len(dat)
  396. self.ser.write(dat[:nr])
  397. self.ser.read(1) # Sync with Greaseweazle
  398. ## bw_stats:
  399. ## Get min/max bandwidth for previous source/sink command. Mbps (float).
  400. def bw_stats(self):
  401. self._send_cmd(struct.pack("3B", Cmd.GetInfo, 3,
  402. GetInfo.BandwidthStats))
  403. min_bytes, min_usecs, max_bytes, max_usecs = struct.unpack(
  404. "<4I16x", self.ser.read(32))
  405. min_bw = (8 * min_bytes) / min_usecs
  406. max_bw = (8 * max_bytes) / max_usecs
  407. return min_bw, max_bw
  408. ##
  409. ## Delay-property public getters and setters:
  410. ## select_delay: Delay (usec) after asserting drive select
  411. ## step_delay: Delay (usec) after issuing a head-step command
  412. ## seek_settle_delay: Delay (msec) after completing a head-seek operation
  413. ## motor_delay: Delay (msec) after turning on drive spindle motor
  414. ## watchdog_delay: Timeout (msec) since last command upon which all
  415. ## drives are deselected and spindle motors turned off
  416. ##
  417. def _set_delays(self):
  418. self._send_cmd(struct.pack("<3B5H", Cmd.SetParams,
  419. 3+5*2, Params.Delays,
  420. self._select_delay, self._step_delay,
  421. self._seek_settle_delay,
  422. self._motor_delay, self._watchdog_delay))
  423. @property
  424. def select_delay(self):
  425. return self._select_delay
  426. @select_delay.setter
  427. def select_delay(self, select_delay):
  428. self._select_delay = select_delay
  429. self._set_delays()
  430. @property
  431. def step_delay(self):
  432. return self._step_delay
  433. @step_delay.setter
  434. def step_delay(self, step_delay):
  435. self._step_delay = step_delay
  436. self._set_delays()
  437. @property
  438. def seek_settle_delay(self):
  439. return self._seek_settle_delay
  440. @seek_settle_delay.setter
  441. def seek_settle_delay(self, seek_settle_delay):
  442. self._seek_settle_delay = seek_settle_delay
  443. self._set_delays()
  444. @property
  445. def motor_delay(self):
  446. return self._motor_delay
  447. @motor_delay.setter
  448. def motor_delay(self, motor_delay):
  449. self._motor_delay = motor_delay
  450. self._set_delays()
  451. @property
  452. def watchdog_delay(self):
  453. return self._watchdog_delay
  454. @watchdog_delay.setter
  455. def watchdog_delay(self, watchdog_delay):
  456. self._watchdog_delay = watchdog_delay
  457. self._set_delays()
  458. # Local variables:
  459. # python-indent: 4
  460. # End: