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