class EPaperDisplay:
- # pylint: disable=too-many-instance-attributes
+ # pylint: disable=too-many-instance-attributes, too-many-statements
"""Manage updating an epaper display over a display bus
This initializes an epaper display and connects it into CircuitPython. Unlike other
color_bits_inverted: bool = False,
highlight_color: int = 0x000000,
refresh_display_command: Union[int, ReadableBuffer],
- refresh_time: float = 40.0,
+ refresh_time: float = 40,
busy_pin: Optional[microcontroller.Pin] = None,
busy_state: bool = True,
seconds_per_frame: float = 180,
if rotation % 90 != 0:
raise ValueError("Display rotation must be in 90 degree increments")
+ self._refreshing = False
color_depth = 1
core_grayscale = True
self._black_bits_inverted = black_bits_inverted
self._write_color_ram_command = write_color_ram_command
self._color_bits_inverted = color_bits_inverted
- self._refresh_time = (
- refresh_time # TODO: Verify we are using seconds instead of ms
- )
+ self._refresh_time_ms = refresh_time * 1000
self._busy_state = busy_state
- self._refreshing = False
self._milliseconds_per_frame = seconds_per_frame * 1000
self._chip_select = (
CHIP_SELECT_TOGGLE_EVERY_BYTE
self._grayscale = grayscale
self._start_sequence = start_sequence
- self._start_up_time = (
- start_up_time # TODO: Verify we are using seconds instead of ms
- )
+ self._start_up_time = start_up_time
self._stop_sequence = stop_sequence
- self._refesh_sequence = refresh_sequence
+ self._refresh_sequence = refresh_sequence
self._busy = None
self._two_byte_sequence_length = two_byte_sequence_length
if busy_pin is not None:
self._busy = DigitalInOut(busy_pin)
self._busy.switch_to_input()
+ self._ticks_disabled = False
+
# Clear the color memory if it isn't in use
if highlight_color == 0x00 and write_color_ram_command != NO_COMMAND:
"""TODO: Clear"""
def show(self, group: Group) -> None:
# pylint: disable=unnecessary-pass
- """Switches to displaying the given group of layers. When group is None, the default
+ """
+ .. note:: `show()` is deprecated and will be removed when CircuitPython 9.0.0
+ is released. Use ``.root_group = group`` instead.
+
+ Switches to displaying the given group of layers. When group is None, the default
CircuitPython terminal will be shown (eventually).
"""
if group is None:
group = circuitpython_splash
self._core.set_root_group(group)
+ def _set_root_group(self, root_group: Group) -> None:
+ ok = self._core.set_root_group(root_group)
+ if not ok:
+ raise ValueError("Group already used")
+
def update_refresh_mode(
self, start_sequence: ReadableBuffer, seconds_per_frame: float
) -> None:
"""Updates the ``start_sequence`` and ``seconds_per_frame`` parameters to enable
varying the refresh mode of the display."""
- # TODO: Implement
+ self._start_sequence = bytearray(start_sequence)
+ self._milliseconds_per_frame = seconds_per_frame * 1000
def refresh(self) -> None:
- # pylint: disable=unnecessary-pass
"""Refreshes the display immediately or raises an exception if too soon. Use
``time.sleep(display.time_to_refresh)`` to sleep until a refresh can occur.
"""
- # TODO: Implement
+ if not self._refresh():
+ raise RuntimeError("Refresh too soon")
+
+ def _refresh(self) -> bool:
+ if self._refreshing and self._busy is not None:
+ if self._busy.value != self._busy_state:
+ self._ticks_disabled = True
+ self._refreshing = False
+ self._send_command_sequence(False, self._stop_sequence)
+ else:
+ return False
+ if self._core.current_group is None:
+ return True
+ # Refresh at seconds per frame rate
+ if self.time_to_refresh > 0:
+ return False
+
+ if not self._core.bus_free():
+ # Can't acquire display bus; skip updating this display. Try next display
+ return False
+
+ areas_to_refresh = self._get_refresh_areas()
+ if not areas_to_refresh:
+ return True
+
+ if self._acep:
+ self._start_refresh()
+ self._clean_area()
+ self._finish_refresh()
+ while self._refreshing:
+ # TODO: Add something here that can change self._refreshing
+ # or add something in _background()
+ pass
+
+ self._start_refresh()
+ for area in areas_to_refresh:
+ self._refresh_area(area)
+ self._finish_refresh()
+
+ return True
+
+ def _release(self) -> None:
+ """Release the display and free its resources"""
+ if self._refreshing:
+ self._wait_for_busy()
+ self._ticks_disabled = True
+ self._refreshing = False
+ # Run stop sequence but don't wait for busy because busy is set when sleeping
+ self._send_command_sequence(False, self._stop_sequence)
+ self._core.release_display_core()
+ if self._busy is not None:
+ self._busy.deinit()
+
+ def _background(self) -> None:
+ """Run background refresh tasks."""
+
+ # Wait until initialized
+ if not hasattr(self, "_core"):
+ return
+
+ if self._ticks_disabled:
+ return
+
+ if self._refreshing:
+ refresh_done = False
+ if self._busy is not None:
+ busy = self._busy.value
+ refresh_done = busy == self._busy_state
+ else:
+ refresh_done = (
+ time.monotonic() * 1000 - self._core.last_refresh
+ > self._refresh_time
+ )
+
+ if refresh_done:
+ self._ticks_disabled = True
+ self._refreshing = False
+ # Run stop sequence but don't wait for busy because busy is set when sleeping
+ self._send_command_sequence(False, self._stop_sequence)
def _get_refresh_areas(self) -> list[Area]:
"""Get a list of areas to be refreshed"""
areas = [self._core.area]
return areas
+ def _refresh_area(self, area: Area) -> bool:
+ """Redraw the area."""
+ # pylint: disable=too-many-locals, too-many-branches
+ clipped = Area()
+ # Clip the area to the display by overlapping the areas.
+ # If there is no overlap then we're done.
+ if not self._core.clip_area(area, clipped):
+ return True
+ subrectangles = 1
+ rows_per_buffer = clipped.height()
+ pixels_per_word = 32 // self._core.colorspace.depth
+ pixels_per_buffer = clipped.size()
+
+ # We should have lots of memory
+ buffer_size = clipped.size() // pixels_per_word
+
+ if clipped.size() > buffer_size * pixels_per_word:
+ rows_per_buffer = buffer_size * pixels_per_word // clipped.width()
+ if rows_per_buffer == 0:
+ rows_per_buffer = 1
+ subrectangles = clipped.height() // rows_per_buffer
+ if clipped.height() % rows_per_buffer != 0:
+ subrectangles += 1
+ pixels_per_buffer = rows_per_buffer * clipped.width()
+ buffer_size = pixels_per_buffer // pixels_per_word
+ if pixels_per_buffer % pixels_per_word:
+ buffer_size += 1
+
+ mask_length = (pixels_per_buffer // 32) + 1 # 1 bit per pixel + 1
+
+ passes = 1
+ if self._write_color_ram_command != NO_COMMAND:
+ passes = 2
+ for pass_index in range(passes):
+ remaining_rows = clipped.height()
+ if self._core.row_command != NO_COMMAND:
+ self._core.set_region_to_update(clipped)
+
+ write_command = self._write_black_ram_command
+ if pass_index == 1:
+ write_command = self._write_color_ram_command
+
+ self._core.begin_transaction()
+ self._core.send(DISPLAY_COMMAND, self._chip_select, bytes([write_command]))
+ self._core.end_transaction()
+
+ for subrect_index in range(subrectangles):
+ subrectangle = Area(
+ x1=clipped.x1,
+ y1=clipped.y1 + rows_per_buffer * subrect_index,
+ x2=clipped.x2,
+ y2=clipped.y1 + rows_per_buffer * (subrect_index + 1),
+ )
+ if remaining_rows < rows_per_buffer:
+ subrectangle.y2 = subrectangle.y1 + remaining_rows
+ remaining_rows -= rows_per_buffer
+
+ subrectangle_size_bytes = subrectangle.size() // (
+ 8 // self._core.colorspace.depth
+ )
+
+ buffer = memoryview(bytearray([0] * (buffer_size * 4))).cast("I")
+ mask = memoryview(bytearray([0] * (mask_length * 4))).cast("I")
+
+ if not self._acep:
+ self._core.colorspace.grayscale = True
+ self._core.colorspace.grayscale_bit = 7
+ if pass_index == 1:
+ if self._grayscale: # 4-color grayscale
+ self._core.colorspace.grayscale_bit = 6
+ self._core.fill_area(subrectangle, mask, buffer)
+ elif self._core.colorspace.tricolor:
+ self._core.colorspace.grayscale = False
+ self._core.fill_area(subrectangle, mask, buffer)
+ elif self._core.colorspace.sevencolor:
+ self._core.fill_area(subrectangle, mask, buffer)
+ else:
+ self._core.fill_area(subrectangle, mask, buffer)
+
+ # Invert it all
+ if (pass_index == 1 and self._color_bits_inverted) or (
+ pass_index == 0 and self._black_bits_inverted
+ ):
+ for i in range(buffer_size):
+ buffer[i] = ~buffer[i]
+
+ if not self._core.begin_transaction():
+ # Can't acquire display bus; skip the rest of the data. Try next display.
+ return False
+ self._core.send(
+ DISPLAY_DATA,
+ self._chip_select,
+ buffer.tobytes()[:subrectangle_size_bytes],
+ )
+ self._core.end_transaction()
+ return True
+
def _send_command_sequence(
self, should_wait_for_busy: bool, sequence: ReadableBuffer
) -> None:
self._core.send(
DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, bytes([command])
)
- self._core.send(
- DISPLAY_DATA,
- CHIP_SELECT_UNTOUCHED,
- data,
- )
+ if data_size > 0:
+ self._core.send(
+ DISPLAY_DATA,
+ CHIP_SELECT_UNTOUCHED,
+ bytes(data),
+ )
self._core.end_transaction()
delay_time_ms = 0
if delay:
if self._two_byte_sequence_length:
i += 1
+ def _start_refresh(self) -> None:
+ # Run start sequence
+ self._core._bus_reset() # pylint: disable=protected-access
+ time.sleep(self._start_up_time)
+ self._send_command_sequence(True, self._start_sequence)
+ self._core.start_refresh()
+
def _finish_refresh(self) -> None:
- self._send_command_sequence(False, self._refesh_sequence)
+ # Actually refresh the display now that all pixel RAM has been updated
+ self._send_command_sequence(False, self._refresh_sequence)
+ self._ticks_disabled = False
self._refreshing = True
self._core.finish_refresh()
def _wait_for_busy(self) -> None:
if self._busy is not None:
- while self._busy.value != self._busy_state:
+ while self._busy.value == self._busy_state:
time.sleep(0.001)
+ def _clean_area(self) -> bool:
+ width = self._core.width
+ height = self._core.height
+
+ buffer = bytearray([0x77] * (width // 2))
+ self._core.begin_transaction()
+ self._core.send(
+ DISPLAY_COMMAND, self._chip_select, bytes([self._write_black_ram_command])
+ )
+ self._core.end_transaction()
+ for _ in range(height):
+ if not self._core.begin_transaction():
+ return False
+ self._core.send(DISPLAY_DATA, self._chip_select, buffer)
+ self._core.end_transaction()
+ return True
+
@property
def rotation(self) -> int:
"""The rotation of the display as an int in degrees"""
if transposed != will_transposed:
self._core.width, self._core.height = self._core.height, self._core.width
self._core.set_rotation(value)
+ if self._core.current_group is not None:
+ self._core.current_group._update_transform( # pylint: disable=protected-access
+ self._core.transform
+ )
@property
def time_to_refresh(self) -> float:
"""Time, in fractional seconds, until the ePaper display can be refreshed."""
- return 0.0 # TODO: Implement
+ if self._core.last_refresh == 0:
+ return 0
+
+ # Refresh at seconds per frame rate
+ elapsed_time = time.monotonic() * 1000 - self._core.last_refresh
+ if elapsed_time > self._milliseconds_per_frame:
+ return 0
+ return self._milliseconds_per_frame - elapsed_time
@property
def busy(self) -> bool:
@property
def bus(self) -> _DisplayBus:
"""Current Display Bus"""
- return self._core._bus
+ return self._core.get_bus()
@property
def root_group(self) -> Group:
"""The root group on the epaper display.
If the root group is set to ``None``, no output will be shown.
"""
- return self._core.root_group
+ return self._core.current_group
@root_group.setter
def root_group(self, new_group: Group) -> None:
- self._core.root_group = new_group
+ self._set_root_group(new_group)