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