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