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