"""MicroPython compatibility for running led-driver patterns under CPython. Installs a ``utime`` module whose clock is chosen per thread: * ``RealClock`` — monotonic wall clock, ``sleep_ms`` really sleeps (render threads). * ``VirtualClock`` — manual time; ``sleep_ms`` just advances it (tests, offline render). Patterns only use ``ticks_ms``/``ticks_diff``/``ticks_add``/``sleep_ms``; tick values never wrap here, so the diff/add helpers are plain arithmetic. """ import sys import threading import time import types class RealClock: def __init__(self): self._t0 = time.monotonic() def ticks_ms(self): return int((time.monotonic() - self._t0) * 1000) def ticks_us(self): return int((time.monotonic() - self._t0) * 1000000) def sleep_ms(self, ms): if ms > 0: time.sleep(ms / 1000.0) class VirtualClock: def __init__(self, start_ms=0): self.now_us = int(start_ms) * 1000 def ticks_ms(self): return self.now_us // 1000 def ticks_us(self): return self.now_us def advance_ms(self, ms): self.now_us += int(ms * 1000) def sleep_ms(self, ms): if ms > 0: self.advance_ms(ms) _local = threading.local() _default_clock = RealClock() def current_clock(): return getattr(_local, "clock", None) or _default_clock def set_thread_clock(clock): """Use ``clock`` for ``utime`` calls made on the current thread (None = real).""" _local.clock = clock def _build_utime(): mod = types.ModuleType("utime") mod.ticks_ms = lambda: current_clock().ticks_ms() mod.ticks_us = lambda: current_clock().ticks_us() mod.ticks_cpu = mod.ticks_us mod.ticks_diff = lambda a, b: a - b mod.ticks_add = lambda a, b: a + b mod.sleep_ms = lambda ms: current_clock().sleep_ms(ms) mod.sleep_us = lambda us: current_clock().sleep_ms(us / 1000.0) mod.sleep = lambda s: current_clock().sleep_ms(s * 1000.0) mod.time = time.time mod.__led_controller_shim__ = True return mod def install(): """Register the shim as ``utime`` (idempotent; never replaces a real utime).""" existing = sys.modules.get("utime") if existing is not None: return existing mod = _build_utime() sys.modules["utime"] = mod return mod