1 """SPI Class for FTDI MPSSE"""
2 from adafruit_blinka.microcontroller.ftdi_mpsse.mpsse.pin import Pin
4 # pylint: disable=protected-access
6 """Custom SPI Class for FTDI MPSSE"""
10 def __init__(self, spi_id=None):
11 # pylint: disable=import-outside-toplevel
12 from pyftdi.spi import SpiController
14 # pylint: enable=import-outside-toplevel
16 self._spi = SpiController(cs_count=1)
18 self._spi.configure("ftdi://ftdi:ft232h/1")
20 self._spi.configure("ftdi://ftdi:ft2232h/{}".format(spi_id + 1))
21 self._port = self._spi.get_port(0)
22 self._port.set_frequency(100000)
25 # Change GPIO controller to SPI
26 Pin.mpsse_gpio = self._spi.get_gpio()
28 # pylint: disable=too-many-arguments,unused-argument
40 """Initialize the Port"""
41 self._port.set_frequency(baudrate)
42 # FTDI device can only support mode 0 and mode 2
43 # due to the limitation of MPSSE engine.
44 # This means CPHA must = 0
45 self._port._cpol = polarity
47 raise ValueError("Only SPI phase 0 is supported by FT232H.")
48 self._port._cpha = phase
50 # pylint: enable=too-many-arguments
54 """Return the current frequency"""
55 return self._port.frequency
57 def write(self, buf, start=0, end=None):
58 """Write data from the buffer to SPI"""
59 end = end if end else len(buf)
60 chunks, rest = divmod(end - start, self._spi.PAYLOAD_MAX_LENGTH)
61 for i in range(chunks):
62 chunk_start = start + i * self._spi.PAYLOAD_MAX_LENGTH
63 chunk_end = chunk_start + self._spi.PAYLOAD_MAX_LENGTH
64 self._port.write(buf[chunk_start:chunk_end])
66 rest_start = start + chunks * self._spi.PAYLOAD_MAX_LENGTH
67 self._port.write(buf[rest_start:end])
69 # pylint: disable=unused-argument
70 def readinto(self, buf, start=0, end=None, write_value=0):
71 """Read data from SPI and into the buffer"""
72 end = end if end else len(buf)
73 buffer_out = [write_value] * (end - start)
74 result = self._port.exchange(buffer_out, end - start, duplex=True)
75 for i, b in enumerate(result):
78 # pylint: enable=unused-argument
80 # pylint: disable=too-many-arguments
82 self, buffer_out, buffer_in, out_start=0, out_end=None, in_start=0, in_end=None
84 """Perform a half-duplex write from buffer_out and then
85 read data into buffer_in
87 out_end = out_end if out_end else len(buffer_out)
88 in_end = in_end if in_end else len(buffer_in)
89 result = self._port.exchange(
90 buffer_out[out_start:out_end], in_end - in_start, duplex=True
92 for i, b in enumerate(result):
93 buffer_in[in_start + i] = b
95 # pylint: enable=too-many-arguments