]> Repositories - hackapet/Adafruit_Blinka_Displayio.git/blob - i2cdisplaybus/__init__.py
make command optional
[hackapet/Adafruit_Blinka_Displayio.git] / i2cdisplaybus / __init__.py
1 # SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams for Adafruit Industries
2 # SPDX-FileCopyrightText: 2020 Erik Tollerud
3 # SPDX-FileCopyrightText: 2021 Jim Morris
4 # SPDX-FileCopyrightText: 2021 James Carr
5 #
6 # SPDX-License-Identifier: MIT
7
8 """
9 `i2cdisplaybus`
10 ================================================================================
11
12 i2cdisplaybus for Blinka
13
14 **Software and Dependencies:**
15
16 * Adafruit Blinka:
17   https://github.com/adafruit/Adafruit_Blinka/releases
18
19 * Author(s): Melissa LeBlanc-Williams, Erik Tollerud, James Carr
20
21 """
22
23 import time
24 from typing import Optional
25
26 import busio
27 import digitalio
28 from circuitpython_typing import ReadableBuffer
29 from displayio._constants import CHIP_SELECT_UNTOUCHED, DISPLAY_COMMAND
30
31 __version__ = "0.0.0+auto.0"
32 __repo__ = "https://github.com/adafruit/Adafruit_Blinka_displayio.git"
33
34
35 class I2CDisplayBus:
36     """Manage updating a display over I2C in the background while Python code runs.
37     It doesn’t handle display initialization.
38     """
39
40     def __init__(self, i2c_bus: busio.I2C, *, device_address: int, reset=None):
41         """Create a I2CDisplayBus object associated with the given I2C bus and reset pin.
42
43         The I2C bus and pins are then in use by the display until displayio.release_displays() is
44         called even after a reload. (It does this so CircuitPython can use the display after your
45         code is done.) So, the first time you initialize a display bus in code.py you should call
46         :py:func`displayio.release_displays` first, otherwise it will error after the first
47         code.py run.
48         """
49
50         if reset is not None:
51             self._reset = digitalio.DigitalInOut(reset)
52             self._reset.switch_to_output(value=True)
53         else:
54             self._reset = None
55         self._i2c = i2c_bus
56         self._dev_addr = device_address
57
58     def __new__(cls, *args, **kwargs):
59         from displayio import (  # pylint: disable=import-outside-toplevel, cyclic-import
60             allocate_display_bus,
61         )
62
63         display_bus_instance = super().__new__(cls)
64         allocate_display_bus(display_bus_instance)
65         return display_bus_instance
66
67     def _release(self):
68         self.reset()
69         self._i2c.deinit()
70         if self._reset is not None:
71             self._reset.deinit()
72
73     def reset(self) -> None:
74         """
75         Performs a hardware reset via the reset pin if one is present.
76         """
77
78         if self._reset is None:
79             return
80
81         self._reset.value = False
82         time.sleep(0.0001)
83         self._reset.value = True
84
85     def send(self, command: int, data: ReadableBuffer) -> None:
86         """
87         Sends the given command value followed by the full set of data. Display state,
88         such as vertical scroll, set via ``send`` may or may not be reset once the code is
89         done.
90         """
91         self._begin_transaction()
92         # re-wrap in case of byte-string
93         #buffer = list(data) if isinstance(data, bytes) else data
94         #self._send(DISPLAY_COMMAND, CHIP_SELECT_UNTOUCHED, bytes([command] + buffer))
95         self._send(DISPLAY_COMMAND, CHIP_SELECT_UNTOUCHED, data, command)
96         self._end_transaction()
97
98     def _send(
99         self,
100         data_type: int,
101         _chip_select: int,  # Chip select behavior
102         data: ReadableBuffer,
103         command: Optional[int] = None,
104     ):
105         if data_type == DISPLAY_COMMAND:
106             n = len(data)
107             if command is not None:
108                 n += 1
109             if n > 0:
110                 command_bytes = bytearray(n * 2)
111                 for i in range(n):
112                     command_bytes[2 * i] = 0x80
113                     if command is not None:
114                         if i > 0:
115                             command_bytes[2 * i + 1] = data[i]
116                         else:
117                             command_bytes[2 * i + 1] = command
118                     else:
119                         command_bytes[2 * i + 1] = data[i]
120
121             try:
122                 self._i2c.writeto(self._dev_addr, buffer=command_bytes)
123             except OSError as error:
124                 if error.errno == 121:
125                     raise RuntimeError(
126                         f"I2C write error to 0x{self._dev_addr:02x}"
127                     ) from error
128                 raise error
129         else:
130             size = len(data) + 1
131             if command is not None:
132                 size += 1
133             data_bytes = bytearray(size)
134             data_bytes[0] = 0x40
135             if command is not None:
136                 data_bytes[1] = command
137                 data_bytes[2:] = data
138             else:
139                 data_bytes[1:] = data
140             try:
141                 self._i2c.writeto(self._dev_addr, buffer=data_bytes)
142             except OSError as error:
143                 if error.errno == 121:
144                     raise RuntimeError(
145                         f"I2C write error to 0x{self._dev_addr:02x}"
146                     ) from error
147                 raise error
148
149     def _free(self) -> bool:
150         """Attempt to free the bus and return False if busy"""
151         if not self._i2c.try_lock():
152             return False
153         self._i2c.unlock()
154         return True
155
156     def _begin_transaction(self) -> bool:
157         """Lock the bus before sending data."""
158         return self._i2c.try_lock()
159
160     def _end_transaction(self) -> None:
161         """Release the bus after sending data."""
162         self._i2c.unlock()