]> Repositories - Adafruit_Blinka-hackapet.git/blob - src/bitbangio.py
Re-ran pre-commit after updating black version
[Adafruit_Blinka-hackapet.git] / src / bitbangio.py
1 # SPDX-FileCopyrightText: 2021 Melissa LeBlanc-Williams for Adafruit Industries
2 #
3 # SPDX-License-Identifier: MIT
4 """
5 `bitbangio` - Bitbanged bus protocols
6 ==============================================================
7
8 See `CircuitPython:bitbangio` in CircuitPython for more details.
9
10 * Author(s): cefn
11 """
12
13 import adafruit_platformdetect.constants.boards as ap_board
14 from adafruit_blinka import Lockable, agnostic
15
16 # pylint: disable=import-outside-toplevel,too-many-arguments
17
18
19 class I2C(Lockable):
20     """Bitbang/Software I2C implementation"""
21
22     def __init__(self, scl, sda, frequency=400000):
23         # TODO: This one is a bit questionable:
24         if agnostic.board_id == ap_board.PYBOARD:
25             raise NotImplementedError("No software I2C on {}".format(agnostic.board_id))
26         if agnostic.detector.board.any_embedded_linux:
27             # TODO: Attempt to load this library automatically
28             raise NotImplementedError(
29                 "For bitbangio on Linux, please use Adafruit_CircuitPython_BitbangIO"
30             )
31         self.init(scl, sda, frequency)
32
33     def init(self, scl, sda, frequency):
34         """Initialization"""
35         from machine import Pin
36         from machine import I2C as _I2C
37
38         self.deinit()
39         id = (  # pylint: disable=redefined-builtin
40             -1
41         )  # force bitbanging implementation - in future
42         # introspect platform if SDA/SCL matches hardware I2C
43         self._i2c = _I2C(id, Pin(scl.id), Pin(sda.id), freq=frequency)
44
45     def deinit(self):
46         """Deinitialization"""
47         try:
48             del self._i2c
49         except AttributeError:
50             pass
51
52     def __enter__(self):
53         return self
54
55     def __exit__(self, exc_type, exc_value, traceback):
56         self.deinit()
57
58     def scan(self):
59         """Scan for attached devices"""
60         return self._i2c.scan()
61
62     def readfrom_into(self, address, buffer, start=0, end=None):
63         """Read from a device at specified address into a buffer"""
64         if start != 0 or end is not None:
65             if end is None:
66                 end = len(buffer)
67             buffer = memoryview(buffer)[start:end]
68         stop = True  # remove for efficiency later
69         return self._i2c.readfrom_into(address, buffer, stop)
70
71     def writeto(self, address, buffer, start=0, end=None, stop=True):
72         """Write to a device at specified address from a buffer"""
73         if start != 0 or end is not None:
74             if end is None:
75                 return self._i2c.writeto(address, memoryview(buffer)[start:], stop)
76             return self._i2c.writeto(address, memoryview(buffer)[start:end], stop)
77         return self._i2c.writeto(address, buffer, stop)
78
79
80 # TODO untested, as actually busio.SPI was on
81 # tasklist https://github.com/adafruit/Adafruit_Micropython_Blinka/issues/2 :(
82 class SPI(Lockable):
83     """Bitbang/Software SPI implementation"""
84
85     def __init__(self, clock, MOSI=None, MISO=None):
86         if agnostic.detector.board.any_embedded_linux:
87             # TODO: Attempt to load this library automatically
88             raise NotImplementedError(
89                 "For bitbangio on Linux, please use Adafruit_CircuitPython_BitbangIO"
90             )
91         from machine import SPI as _SPI
92
93         self._spi = _SPI(-1)
94         self._pins = (clock, MOSI, MISO)
95
96     def configure(self, baudrate=100000, polarity=0, phase=0, bits=8):
97         """Update the configuration"""
98         from machine import Pin
99         from machine import SPI as _SPI
100
101         if self._locked:
102             # TODO verify if _spi obj 'caches' sck, mosi, miso to
103             # avoid storing in _attributeIds (duplicated in busio)
104             # i.e. #init ignores MOSI=None rather than unsetting
105             self._spi.init(
106                 baudrate=baudrate,
107                 polarity=polarity,
108                 phase=phase,
109                 bits=bits,
110                 firstbit=_SPI.MSB,
111                 sck=Pin(self._pins[0].id),
112                 mosi=Pin(self._pins[1].id),
113                 miso=Pin(self._pins[2].id),
114             )
115         else:
116             raise RuntimeError("First call try_lock()")
117
118     def write(self, buf):
119         """Write to the SPI device"""
120         return self._spi.write(buf)
121
122     def readinto(self, buf):
123         """Read from the SPI device into a buffer"""
124         return self.readinto(buf)
125
126     def write_readinto(self, buffer_out, buffer_in):
127         """Write to the SPI device and read from the SPI device into a buffer"""
128         return self.write_readinto(buffer_out, buffer_in)