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