#!/usr/bin/env python3 """Reusable NanoPi NEO2 / ILI9341 animation player for optimized .nvd files. Example: with AnimationPlayer('/root/Nova/animation/compiled') as player: player.play('blinking') player.play('heart-eying', loops=2, fps=30) """ import argparse import signal import struct import time from pathlib import Path WIDTH, HEIGHT = 320, 240 DC, RST = 7, 12 # Physical NanoPi pins, GPIO.BOARD numbering SPI_HZ = 32_000_000 HEADER = struct.Struct("<8sHHHI") RECT = struct.Struct(" 8: raise ValueError(f"Too many rectangles in {path}") rectangles = [] for _ in range(rect_count): x, y, w, h = RECT.unpack(read_exact(stream, RECT.size)) if x + w > width or y + h > height or bool(w) != bool(h): raise ValueError(f"Invalid rectangle in {path}") pixels = read_exact(stream, w * h * 2) if w and h: rectangles.append((x, y, w, h, pixels)) transitions.append(rectangles) if stream.read(1): raise ValueError(f"Unexpected trailing data in {path}") return fps, first, transitions def send_rect(serial, x, y, width, height, pixels): x_end, y_end = x + width - 1, y + height - 1 serial.command(0x2A) serial.data(bytes((x >> 8, x & 255, x_end >> 8, x_end & 255))) serial.command(0x2B) serial.data(bytes((y >> 8, y & 255, y_end >> 8, y_end & 255))) serial.command(0x2C) serial.data(pixels) class AnimationPlayer: """Play named animations synchronously, reusing one LCD connection. ``play(name, loops=1)`` plays once and returns. Set ``loops=None`` to repeat until ``stop()`` is called (from another thread or a signal handler). Call ``close()`` when finished, or use a ``with`` block. """ def __init__(self, directory=None, rotation=180): if rotation not in (0, 180): raise ValueError("rotation must be 0 or 180 degrees") self.directory = Path(directory) if directory else Path(__file__).resolve().parent / "animation" / "compiled" self.rotation = rotation self.serial = None self._cache = {} self._stop_requested = False def names(self): return sorted(path.stem for path in self.directory.glob("*.nvd")) def load(self, name): if not name or name in (".", "..") or "/" in name or "\\" in name: raise ValueError("Use an animation name from names()") if name not in self._cache: path = self.directory / f"{name}.nvd" if not path.is_file(): raise FileNotFoundError(f"Unknown animation {name!r}; available: {', '.join(self.names())}") self._cache[name] = load_animation(path) return self._cache[name] def open(self): if self.serial is not None: return self import NPi.GPIO as GPIO from luma.core.interface.serial import spi from luma.lcd.device import ili9341 GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) serial = spi( gpio=GPIO, port=0, device=0, bus_speed_hz=SPI_HZ, transfer_size=4096, gpio_DC=DC, gpio_RST=RST, reset_hold_time=0.10, reset_release_time=0.15, ) try: ili9341(serial, gpio=GPIO, width=WIDTH, height=HEIGHT, rotate=0) # luma initializes landscape as MADCTL 0x28. Reversing both axes # turns the same 320x240 pixel stream through 180 degrees. serial.command(0x36) serial.data(bytes((0xE8 if self.rotation == 180 else 0x28,))) serial.command(0x3A) # RGB565: two bytes per pixel. serial.data(bytes((0x55,))) except BaseException: serial.cleanup() raise self.serial = serial return self def close(self): if self.serial is not None: self.serial.cleanup() self.serial = None def stop(self): self._stop_requested = True def play(self, name, loops=1, fps=None, progress=None): if loops is not None and (not isinstance(loops, int) or loops < 1): raise ValueError("loops must be a positive integer or None") stored_fps, first, transitions = self.load(name) rate = stored_fps if fps is None else fps if rate <= 0: raise ValueError("fps must be positive") self.open() self._stop_requested = False started = time.monotonic() send_rect(self.serial, 0, 0, WIDTH, HEIGHT, first) period = 1.0 / rate deadline = time.monotonic() + period report_at = time.monotonic() report_frames = report_updates = 0 frame_count = 0 cycle = 0 while not self._stop_requested and (loops is None or cycle < loops): for rectangles in transitions: if self._stop_requested: break delay = deadline - time.monotonic() if delay > 0: time.sleep(delay) for rectangle in rectangles: send_rect(self.serial, *rectangle) report_updates += 1 frame_count += 1 report_frames += 1 deadline += period now = time.monotonic() if now > deadline: deadline = now + period if progress is not None and now - report_at >= 5: elapsed = now - report_at progress(report_frames / elapsed, report_updates / elapsed) report_at = now report_frames = report_updates = 0 cycle += 1 return {"name": name, "frames": frame_count, "seconds": time.monotonic() - started} def __enter__(self): return self.open() def __exit__(self, _type, _value, _traceback): self.close() def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("name", nargs="?", help="Animation folder name, such as blinking") parser.add_argument("--directory", type=Path, default=Path(__file__).resolve().parent / "animation" / "compiled") parser.add_argument("--list", action="store_true", help="List available animations") parser.add_argument("--loops", type=int, default=1) parser.add_argument("--forever", action="store_true") parser.add_argument("--fps", type=float, help="Override the stored playback rate") parser.add_argument("--rotation", type=int, choices=(0, 180), default=180) args = parser.parse_args() player = AnimationPlayer(args.directory, rotation=args.rotation) if args.list: print("\n".join(player.names())) return if not args.name: parser.error("Provide an animation name or --list") def request_stop(_signum, _frame): player.stop() signal.signal(signal.SIGINT, request_stop) signal.signal(signal.SIGTERM, request_stop) with player: result = player.play(args.name, loops=None if args.forever else args.loops, fps=args.fps, progress=lambda frames, updates: print( f"Sequence: {frames:.1f} FPS; LCD updates: {updates:.1f}/s", flush=True)) print(f"Played {result['name']}: {result['frames']} frames in {result['seconds']:.1f}s") if __name__ == "__main__": main()