]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/busio.py
renamed spi/i2c to generic linux since they're not platform specific
[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" or board_id == "beaglebone_black":
20             from adafruit_blinka.microcontroller.generic_linux.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=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=stop)
61             else:
62                 return self._i2c.writeto(address, memoryview(buffer)[start:end], stop=stop)
63         return self._i2c.writeto(address, buffer, stop=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.writeto_then_readfrom(address, buffer_out, buffer_in,
67                                                out_start=out_start, out_end=out_end,
68                                                in_start=in_start, in_end=in_end, stop=stop)
69
70 class SPI(Lockable):
71     def __init__(self, clock, MOSI=None, MISO=None):
72         print("SPI(): __init()")
73         self.deinit()
74         if board_id == "raspi_3" or board_id == "raspi_2" or board_id == "beaglebone_black":
75             from adafruit_blinka.microcontroller.generic_linux.spi import SPI as _SPI
76         else:
77             from machine import SPI as _SPI
78         from microcontroller.pin import spiPorts
79         print("spiPorts: {0}".format(spiPorts))
80         print("for:")
81         for portId, portSck, portMosi, portMiso in spiPorts:
82             print(portId, portSck, portMosi, portMiso)
83             if ((clock == portSck) and                   # Clock is required!
84                 (MOSI == portMosi or MOSI == None) and   # But can do with just output
85                 (MISO == portMiso or MISO == None)):      # Or just input
86                 print("Line 91")
87                 print(_SPI)
88                 print(_SPI(portId))
89                 self._spi = _SPI(portId)
90                 self._pins = (portSck, portMosi, portMiso)
91                 break
92         else:
93             raise NotImplementedError(
94                 "No Hardware SPI on (SCLK, MOSI, MISO)={}\nValid SPI ports:{}".
95                 format((clock, MOSI, MISO), spiPorts))
96
97     def configure(self, baudrate=100000, polarity=0, phase=0, bits=8):
98         if board_id == "raspi_3" or board_id == "raspi_2":
99             from adafruit_blinka.microcontroller.raspi_23.pin import Pin
100             from adafruit_blinka.microcontroller.generic_linux.spi import SPI as _SPI
101         elif board_id == "beaglebone_black":
102             # reuse the raspberry pi class as both boards use Linux spidev
103             from adafruit_blinka.microcontroller.beaglebone_black.pin import Pin
104             from adafruit_blinka.microcontroller.generic_linux.spi import SPI as _SPI
105         else:
106             from machine import SPI as _SPI
107             from machine import Pin
108
109         if self._locked:
110             # TODO check if #init ignores MOSI=None rather than unsetting, to save _pinIds attribute
111             self._spi.init(
112                 baudrate=baudrate,
113                 polarity=polarity,
114                 phase=phase,
115                 bits=bits,
116                 firstbit=_SPI.MSB,
117                 sck=Pin(self._pins[0].id),
118                 mosi=Pin(self._pins[1].id),
119                 miso=Pin(self._pins[2].id)
120             )
121         else:
122             raise RuntimeError("First call try_lock()")
123
124     def deinit(self):
125         self._spi = None
126         self._pinIds = None
127
128     def write(self, buf, start=0, end=None):
129         return self._spi.write(buf, start, end)
130
131     def readinto(self, buf, start=0, end=None, write_value=0):
132         return self._spi.readinto(buf, start, end)
133
134     def write_readinto(self, buffer_out, buffer_in,  out_start=0, out_end=None, in_start=0, in_end=None):
135         return self._spi.write_readinto(buffer_out, buffer_in, out_start, out_end, in_start, in_end)
136
137
138 class UART(Lockable):
139     class Parity(Enum):
140         pass
141
142     Parity.ODD = Parity()
143     Parity.EVEN = Parity()
144
145     def __init__(self,
146                  tx,
147                  rx,
148                  baudrate=9600,
149                  bits=8,
150                  parity=None,
151                  stop=1,
152                  timeout=1000,
153                  receiver_buffer_size=64,
154                  flow=None):
155         from machine import UART as _UART
156         from microcontroller.pin import uartPorts
157
158         self.baudrate = baudrate
159
160         if flow is not None:  # default 0
161             raise NotImplementedError(
162                 "Parameter '{}' unsupported on {}".format(
163                     "flow", agnostic.board))
164
165         # translate parity flag for Micropython
166         if parity is UART.Parity.ODD:
167             parity = 1
168         elif parity is UART.Parity.EVEN:
169             parity = 0
170         elif parity is None:
171             pass
172         else:
173             raise ValueError("Invalid parity")
174
175         # check tx and rx have hardware support
176         for portId, portTx, portRx in uartPorts:  #
177             if portTx == tx and portRx == rx:
178                 self._uart = _UART(
179                     portId,
180                     baudrate,
181                     bits=bits,
182                     parity=parity,
183                     stop=stop,
184                     timeout=timeout,
185                     read_buf_len=receiver_buffer_size
186                 )
187                 break
188         else:
189             raise NotImplementedError(
190                 "No Hardware UART on (tx,rx)={}\nValid UART ports".format(
191                     (tx, rx), uartPorts))
192
193     def deinit(self):
194         self._uart = None
195
196     def read(self, nbytes=None):
197         return self._uart.read(nbytes)
198
199     def readinto(self, buf, nbytes=None):
200         return self._uart.readinto(buf, nbytes)
201
202     def readline(self):
203         return self._uart.readline()
204
205     def write(self, buf):
206         return self._uart.write(buf)