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