]> Repositories - hackapet/Adafruit_Blinka_Displayio.git/blob - displayio/display.py
Merge pull request #17 from makermelissa/rotation
[hackapet/Adafruit_Blinka_Displayio.git] / displayio / display.py
1 # The MIT License (MIT)
2 #
3 # Copyright (c) 2020 Melissa LeBlanc-Williams for Adafruit Industries
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a copy
6 # of this software and associated documentation files (the "Software"), to deal
7 # in the Software without restriction, including without limitation the rights
8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 # copies of the Software, and to permit persons to whom the Software is
10 # furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice shall be included in
13 # all copies or substantial portions of the Software.
14 #
15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 # THE SOFTWARE.
22
23 """
24 `displayio.display`
25 ================================================================================
26
27 displayio for Blinka
28
29 **Software and Dependencies:**
30
31 * Adafruit Blinka:
32   https://github.com/adafruit/Adafruit_Blinka/releases
33
34 * Author(s): Melissa LeBlanc-Williams
35
36 """
37
38 import time
39 import struct
40 import threading
41 from PIL import Image
42 import numpy
43 from recordclass import recordclass
44
45 __version__ = "0.0.0-auto.0"
46 __repo__ = "https://github.com/adafruit/Adafruit_Blinka_displayio.git"
47
48 Rectangle = recordclass("Rectangle", "x1 y1 x2 y2")
49 displays = []
50
51 # pylint: disable=unnecessary-pass, unused-argument
52
53 # pylint: disable=too-many-instance-attributes
54 class Display:
55     """This initializes a display and connects it into CircuitPython. Unlike other objects
56     in CircuitPython, Display objects live until ``displayio.release_displays()`` is called.
57     This is done so that CircuitPython can use the display itself.
58
59     Most people should not use this class directly. Use a specific display driver instead
60     that will contain the initialization sequence at minimum.
61
62     .. class::
63         Display(display_bus, init_sequence, *, width, height, colstart=0, rowstart=0, rotation=0,
64         color_depth=16, grayscale=False, pixels_in_byte_share_row=True, bytes_per_cell=1,
65         reverse_pixels_in_byte=False, set_column_command=0x2a, set_row_command=0x2b,
66         write_ram_command=0x2c, set_vertical_scroll=0, backlight_pin=None, brightness_command=None,
67         brightness=1.0, auto_brightness=False, single_byte_bounds=False, data_as_commands=False,
68         auto_refresh=True, native_frames_per_second=60)
69     """
70
71     # pylint: disable=too-many-locals
72     def __init__(
73         self,
74         display_bus,
75         init_sequence,
76         *,
77         width,
78         height,
79         colstart=0,
80         rowstart=0,
81         rotation=0,
82         color_depth=16,
83         grayscale=False,
84         pixels_in_byte_share_row=True,
85         bytes_per_cell=1,
86         reverse_pixels_in_byte=False,
87         set_column_command=0x2A,
88         set_row_command=0x2B,
89         write_ram_command=0x2C,
90         set_vertical_scroll=0,
91         backlight_pin=None,
92         brightness_command=None,
93         brightness=1.0,
94         auto_brightness=False,
95         single_byte_bounds=False,
96         data_as_commands=False,
97         auto_refresh=True,
98         native_frames_per_second=60
99     ):
100         """Create a Display object on the given display bus (`displayio.FourWire` or
101         `displayio.ParallelBus`).
102
103         The ``init_sequence`` is bitpacked to minimize the ram impact. Every command begins
104         with a command byte followed by a byte to determine the parameter count and if a
105         delay is need after. When the top bit of the second byte is 1, the next byte will be
106         the delay time in milliseconds. The remaining 7 bits are the parameter count
107         excluding any delay byte. The third through final bytes are the remaining command
108         parameters. The next byte will begin a new command definition. Here is a portion of
109         ILI9341 init code:
110         .. code-block:: python
111
112             init_sequence = (
113                 b"\xe1\x0f\x00\x0E\x14\x03\x11\x07\x31\xC1\x48\x08\x0F\x0C\x31\x36\x0F"
114                 b"\x11\x80\x78"# Exit Sleep then delay 0x78 (120ms)
115                 b"\x29\x80\x78"# Display on then delay 0x78 (120ms)
116             )
117             display = displayio.Display(display_bus, init_sequence, width=320, height=240)
118
119         The first command is 0xe1 with 15 (0xf) parameters following. The second and third
120         are 0x11 and 0x29 respectively with delays (0x80) of 120ms (0x78) and no parameters.
121         Multiple byte literals (b”“) are merged together on load. The parens are needed to
122         allow byte literals on subsequent lines.
123
124         The initialization sequence should always leave the display memory access inline with
125         the scan of the display to minimize tearing artifacts.
126         """
127         self._bus = display_bus
128         self._set_column_command = set_column_command
129         self._set_row_command = set_row_command
130         self._write_ram_command = write_ram_command
131         self._brightness_command = brightness_command
132         self._data_as_commands = data_as_commands
133         self._single_byte_bounds = single_byte_bounds
134         self._width = width
135         self._height = height
136         self._colstart = colstart
137         self._rowstart = rowstart
138         self._rotation = rotation
139         self._auto_brightness = auto_brightness
140         self._brightness = brightness
141         self._auto_refresh = auto_refresh
142         self._initialize(init_sequence)
143         self._buffer = Image.new("RGB", (width, height))
144         self._subrectangles = []
145         self._bounds_encoding = ">BB" if single_byte_bounds else ">HH"
146         self._current_group = None
147         displays.append(self)
148         self._refresh_thread = None
149         if self._auto_refresh:
150             self.auto_refresh = True
151
152     # pylint: enable=too-many-locals
153
154     def _initialize(self, init_sequence):
155         i = 0
156         while i < len(init_sequence):
157             command = init_sequence[i]
158             data_size = init_sequence[i + 1]
159             delay = (data_size & 0x80) > 0
160             data_size &= ~0x80
161             self._write(command, init_sequence[i + 2 : i + 2 + data_size])
162             delay_time_ms = 10
163             if delay:
164                 data_size += 1
165                 delay_time_ms = init_sequence[i + 1 + data_size]
166                 if delay_time_ms == 255:
167                     delay_time_ms = 500
168             time.sleep(delay_time_ms / 1000)
169             i += 2 + data_size
170
171     def _write(self, command, data):
172         if self._single_byte_bounds:
173             self._bus.send(True, bytes([command]) + data, toggle_every_byte=True)
174         else:
175             self._bus.send(True, bytes([command]), toggle_every_byte=True)
176             self._bus.send(False, data)
177
178     def _release(self):
179         self._bus.release()
180         self._bus = None
181
182     def show(self, group):
183         """Switches to displaying the given group of layers. When group is None, the
184         default CircuitPython terminal will be shown.
185         """
186         self._current_group = group
187
188     def refresh(self, *, target_frames_per_second=60, minimum_frames_per_second=1):
189         """When auto refresh is off, waits for the target frame rate and then refreshes the
190         display, returning True. If the call has taken too long since the last refresh call
191         for the given target frame rate, then the refresh returns False immediately without
192         updating the screen to hopefully help getting caught up.
193
194         If the time since the last successful refresh is below the minimum frame rate, then
195         an exception will be raised. Set minimum_frames_per_second to 0 to disable.
196
197         When auto refresh is on, updates the display immediately. (The display will also
198         update without calls to this.)
199         """
200         # Go through groups and and add each to buffer
201         if self._current_group is not None:
202             buffer = Image.new("RGBA", (self._width, self._height))
203             # Recursively have everything draw to the image
204             self._current_group._fill_area(buffer)  # pylint: disable=protected-access
205             # save image to buffer (or probably refresh buffer so we can compare)
206             self._buffer.paste(buffer)
207
208         # Eventually calculate dirty rectangles here
209         self._subrectangles.append(Rectangle(0, 0, self._width, self._height))
210
211         for area in self._subrectangles:
212             self._refresh_display_area(area)
213
214     def _refresh_loop(self):
215         while self._auto_refresh:
216             self.refresh()
217
218     def _refresh_display_area(self, rectangle):
219         """Loop through dirty rectangles and redraw that area."""
220
221         img = self._buffer.crop(rectangle).convert("RGB")
222         img = img.rotate(self._rotation)
223
224         data = numpy.array(img).astype("uint16")
225         color = (
226             ((data[:, :, 0] & 0xF8) << 8)
227             | ((data[:, :, 1] & 0xFC) << 3)
228             | (data[:, :, 2] >> 3)
229         )
230
231         pixels = list(
232             numpy.dstack(((color >> 8) & 0xFF, color & 0xFF)).flatten().tolist()
233         )
234
235         display_rectangle = self._apply_rotation(rectangle)
236
237         self._write(
238             self._set_column_command,
239             self._encode_pos(
240                 display_rectangle.x1 + self._colstart,
241                 display_rectangle.x2 + self._colstart - 1,
242             ),
243         )
244         self._write(
245             self._set_row_command,
246             self._encode_pos(
247                 display_rectangle.y1 + self._rowstart,
248                 display_rectangle.y2 + self._rowstart - 1,
249             ),
250         )
251
252         self._write(self._write_ram_command, pixels)
253
254     def _apply_rotation(self, rectangle):
255         """Adjust the rectangle coordinates based on rotation"""
256         if self._rotation == 90:
257             return Rectangle(
258                 self._width - rectangle.y2,
259                 rectangle.x1,
260                 self._width - rectangle.y1,
261                 rectangle.x2,
262             )
263         if self._rotation == 180:
264             return Rectangle(
265                 self._width - rectangle.x2,
266                 self._height - rectangle.y2,
267                 self._width - rectangle.x1,
268                 self._height - rectangle.y1,
269             )
270         if self._rotation == 270:
271             return Rectangle(
272                 rectangle.y1,
273                 self._height - rectangle.x2,
274                 rectangle.y2,
275                 self._height - rectangle.x1,
276             )
277         return rectangle
278
279     def _encode_pos(self, x, y):
280         """Encode a postion into bytes."""
281         return struct.pack(self._bounds_encoding, x, y)
282
283     def fill_row(self, y, buffer):
284         """Extract the pixels from a single row"""
285         pass
286
287     @property
288     def auto_refresh(self):
289         """True when the display is refreshed automatically."""
290         return self._auto_refresh
291
292     @auto_refresh.setter
293     def auto_refresh(self, value):
294         self._auto_refresh = value
295         if self._refresh_thread is None:
296             self._refresh_thread = threading.Thread(
297                 target=self._refresh_loop, daemon=True
298             )
299         if value and not self._refresh_thread.is_alive():
300             # Start the thread
301             self._refresh_thread.start()
302         elif not value and self._refresh_thread.is_alive():
303             # Stop the thread
304             self._refresh_thread.join()
305
306     @property
307     def brightness(self):
308         """The brightness of the display as a float. 0.0 is off and 1.0 is full `brightness`.
309         When `auto_brightness` is True, the value of `brightness` will change automatically.
310         If `brightness` is set, `auto_brightness` will be disabled and will be set to False.
311         """
312         return self._brightness
313
314     @brightness.setter
315     def brightness(self, value):
316         self._brightness = value
317
318     @property
319     def auto_brightness(self):
320         """True when the display brightness is adjusted automatically, based on an ambient
321         light sensor or other method. Note that some displays may have this set to True by
322         default, but not actually implement automatic brightness adjustment.
323         `auto_brightness` is set to False if `brightness` is set manually.
324         """
325         return self._auto_brightness
326
327     @auto_brightness.setter
328     def auto_brightness(self, value):
329         self._auto_brightness = value
330
331     @property
332     def width(self):
333         """Display Width"""
334         return self._width
335
336     @property
337     def height(self):
338         """Display Height"""
339         return self._height
340
341     @property
342     def rotation(self):
343         """The rotation of the display as an int in degrees."""
344         return self._rotation
345
346     @rotation.setter
347     def rotation(self, value):
348         if value not in (0, 90, 180, 270):
349             raise ValueError("Rotation must be 0/90/180/270")
350         self._rotation = value
351
352     @property
353     def bus(self):
354         """Current Display Bus"""
355         return self._bus
356
357
358 # pylint: enable=too-many-instance-attributes