]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/busio.py
Add writeto_then_readfrom for non-stop transactions on linux
[Adafruit_Blinka-hackapet.git] / src / busio.py
1 """
2 `busio` - Bus protocol support like I2C and SPI
3 =================================================
4
5 See `CircuitPython:busio` in CircuitPython for more details.
6
7 * Author(s): cefn
8 """
9
10 from adafruit_blinka import Enum, Lockable, agnostic
11 from adafruit_blinka.agnostic import board_id
12
13 class I2C(Lockable):
14     def __init__(self, scl, sda, frequency=400000):
15         self.init(scl, sda, frequency)
16
17     def init(self, scl, sda, frequency):
18         self.deinit()
19         if board_id == "raspi_3" or board_id == "raspi_2":
20             from adafruit_blinka.microcontroller.raspi_23.i2c import I2C as _I2C
21         else:
22             from machine import I2C as _I2C
23         from microcontroller.pin import i2cPorts
24         for portId, portScl, portSda in i2cPorts:
25             if scl == portScl and sda == portSda:
26                 self._i2c = _I2C(portId, mode=_I2C.MASTER, baudrate=frequency)
27                 break
28         else:
29             raise NotImplementedError("No Hardware I2C on (scl,sda)={}\nValid UART ports".format(
30         (scl, sda), i2cPorts))
31
32     def deinit(self):
33         try:
34             del self._i2c
35         except AttributeError:
36             pass
37
38     def __enter__(self):
39         return self
40
41     def __exit__(self, exc_type, exc_value, traceback):
42         self.deinit()
43
44     def scan(self):
45         return self._i2c.scan()
46
47     def readfrom_into(self, address, buffer, start=0, end=None):
48         if start is not 0 or end is not None:
49             if end is None:
50                 end = len(buffer)
51             buffer = memoryview(buffer)[start:end]
52         stop = True  # remove for efficiency later
53         return self._i2c.readfrom_into(address, buffer, stop)
54
55     def writeto(self, address, buffer, start=0, end=None, stop=True):
56         if isinstance(buffer, str):
57             buffer = bytes([ord(x) for x in buffer])
58         if start is not 0 or end is not None:
59             if end is None:
60                 return self._i2c.writeto(address, memoryview(buffer)[start:], stop)
61             else:
62                 return self._i2c.writeto(address, memoryview(buffer)[start:end], stop)
63         return self._i2c.writeto(address, buffer, stop)
64
65     def writeto_then_readfrom(self, address, buffer_out, buffer_in, out_start=0, out_end=None, in_start=0, in_end=None, stop=False):
66         return self._i2c.write_readinto(address, buffer_out, buffer_in, out_start, out_end, in_start, in_end, stop)
67
68 class SPI(Lockable):
69     def __init__(self, clock, MOSI=None, MISO=None):
70         self.deinit()
71         if board_id == "raspi_3" or board_id == "raspi_2":
72             from adafruit_blinka.microcontroller.raspi_23.spi import SPI as _SPI
73         else:
74             from machine import SPI as _SPI
75         from microcontroller.pin import spiPorts
76         for portId, portSck, portMosi, portMiso in spiPorts:
77             if ((clock == portSck) and                   # Clock is required!
78                 (MOSI == portMosi or MOSI == None) and   # But can do with just output
79                 (MISO == portMiso or MISO == None)):      # Or just input
80                 self._spi = _SPI(portId)
81                 self._pins = (portSck, portMosi, portMiso)
82                 break
83         else:
84             raise NotImplementedError(
85                 "No Hardware SPI on (SCLK, MOSI, MISO)={}\nValid SPI ports:{}".
86                 format((clock, MOSI, MISO), spiPorts))
87
88     def configure(self, baudrate=100000, polarity=0, phase=0, bits=8):
89         if board_id == "raspi_3" or board_id == "raspi_2":
90             from adafruit_blinka.microcontroller.raspi_23.spi import SPI as _SPI
91             from adafruit_blinka.microcontroller.raspi_23.pin import Pin
92         else:
93             from machine import SPI as _SPI
94             from machine import Pin
95
96         if self._locked:
97             # TODO check if #init ignores MOSI=None rather than unsetting, to save _pinIds attribute
98             self._spi.init(
99                 baudrate=baudrate,
100                 polarity=polarity,
101                 phase=phase,
102                 bits=bits,
103                 firstbit=_SPI.MSB,
104                 sck=Pin(self._pins[0].id),
105                 mosi=Pin(self._pins[1].id),
106                 miso=Pin(self._pins[2].id)
107             )
108         else:
109             raise RuntimeError("First call try_lock()")
110
111     def deinit(self):
112         self._spi = None
113         self._pinIds = None
114
115     def write(self, buf, start=0, end=None):
116         return self._spi.write(buf, start, end)
117
118     def readinto(self, buf, start=0, end=None, write_value=0):
119         return self._spi.readinto(buf, start, end)
120
121     def write_readinto(self, buffer_out, buffer_in,  out_start=0, out_end=None, in_start=0, in_end=None):
122         return self._spi.write_readinto(buffer_out, buffer_in, out_start, out_end, in_start, in_end)
123
124
125 class UART(Lockable):
126     class Parity(Enum):
127         pass
128
129     Parity.ODD = Parity()
130     Parity.EVEN = Parity()
131
132     def __init__(self,
133                  tx,
134                  rx,
135                  baudrate=9600,
136                  bits=8,
137                  parity=None,
138                  stop=1,
139                  timeout=1000,
140                  receiver_buffer_size=64,
141                  flow=None):
142         from machine import UART as _UART
143         from microcontroller.pin import uartPorts
144
145         self.baudrate = baudrate
146
147         if flow is not None:  # default 0
148             raise NotImplementedError(
149                 "Parameter '{}' unsupported on {}".format(
150                     "flow", agnostic.board))
151
152         # translate parity flag for Micropython
153         if parity is UART.Parity.ODD:
154             parity = 1
155         elif parity is UART.Parity.EVEN:
156             parity = 0
157         elif parity is None:
158             pass
159         else:
160             raise ValueError("Invalid parity")
161
162         # check tx and rx have hardware support
163         for portId, portTx, portRx in uartPorts:  #
164             if portTx == tx and portRx == rx:
165                 self._uart = _UART(
166                     portId,
167                     baudrate,
168                     bits=bits,
169                     parity=parity,
170                     stop=stop,
171                     timeout=timeout,
172                     read_buf_len=receiver_buffer_size
173                 )
174                 break
175         else:
176             raise NotImplementedError(
177                 "No Hardware UART on (tx,rx)={}\nValid UART ports".format(
178                     (tx, rx), uartPorts))
179
180     def deinit(self):
181         self._uart = None
182
183     def read(self, nbytes=None):
184         return self._uart.read(nbytes)
185
186     def readinto(self, buf, nbytes=None):
187         return self._uart.readinto(buf, nbytes)
188
189     def readline(self):
190         return self._uart.readline()
191
192     def write(self, buf):
193         return self._uart.write(buf)