1 """Generic Linux SPI class using PureIO's SPI class"""
2 import Adafruit_PureIO.spi as spi
3 from adafruit_blinka.agnostic import detector
18 def __init__(self, portid):
19 if isinstance(portid, tuple):
20 self._spi = spi.SPI(device=portid)
22 self._spi = spi.SPI(device=(portid, 0))
28 # pylint: disable=too-many-arguments,unused-argument
46 self.baudrate = baudrate
49 self.chip = detector.chip
56 # pylint: enable=too-many-arguments,unused-argument
58 # pylint: disable=unnecessary-pass
60 """Setting so that SPI doesn't automatically set the CS pin"""
61 # No kernel seems to support this, so we're just going to pass
64 # pylint: enable=unnecessary-pass
68 """Return the current baudrate"""
71 def write(self, buf, start=0, end=None):
72 """Write data from the buffer to SPI"""
78 # self._spi.open(self._port, 0)
80 self._spi.max_speed_hz = self.baudrate
81 self._spi.mode = self.mode
82 self._spi.bits_per_word = self.bits
83 self._spi.writebytes(buf[start:end])
85 except FileNotFoundError:
86 print("Could not open SPI device - check if SPI is enabled in kernel!")
89 def readinto(self, buf, start=0, end=None, write_value=0):
90 """Read data from SPI and into the buffer"""
96 # self._spi.open(self._port, 0)
98 self._spi.max_speed_hz = self.baudrate
99 self._spi.mode = self.mode
100 self._spi.bits_per_word = self.bits
101 data = self._spi.transfer([write_value] * (end - start))
102 for i in range(end - start): # 'readinto' the given buffer
103 buf[start + i] = data[i]
105 except FileNotFoundError:
106 print("Could not open SPI device - check if SPI is enabled in kernel!")
109 # pylint: disable=too-many-arguments
111 self, buffer_out, buffer_in, out_start=0, out_end=None, in_start=0, in_end=None
113 """Perform a half-duplex write from buffer_out and then
114 read data into buffer_in
116 if not buffer_out or not buffer_in:
119 out_end = len(buffer_out)
121 in_end = len(buffer_in)
122 if out_end - out_start != in_end - in_start:
123 raise RuntimeError("Buffer slices must be of equal length.")
125 # self._spi.open(self._port, 0)
127 self._spi.max_speed_hz = self.baudrate
128 self._spi.mode = self.mode
129 self._spi.bits_per_word = self.bits
130 data = self._spi.transfer(list(buffer_out[out_start : out_end + 1]))
131 for i in range((in_end - in_start)):
132 buffer_in[i + in_start] = data[i]
134 except FileNotFoundError:
135 print("Could not open SPI device - check if SPI is enabled in kernel!")
138 # pylint: enable=too-many-arguments