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