"""Link between one simulated led-driver (Pyodide, in a web worker) and the page (via ``_simlink``). Not a MicroPython module. ``web/driver-worker.js`` defines these functions on the worker global before the driver boots: - ``simRecv()`` next received ESP-NOW frame ``src_mac(6) + packet`` as a Uint8Array, or ``undefined``. Frames come from a SharedArrayBuffer ring the page writes, so they arrive even though ``main.py`` never yields to the JS event loop. - ``simPending()`` number of frames waiting in the ring - ``simTx(u8)`` transmit ``dest_mac(6) + packet`` - ``simPixels(u8)`` latest strip frame, RGB bytes - ``simFlash(path, text)`` persist a flash file (settings.json, presets.json) - ``simSleep(ms)`` block without spinning (``Atomics.wait``) ``machine.WDT.feed()`` calls :func:`on_feed` once per driver main-loop pass. """ import os import random import time import js FLASH_FILES = ("settings.json", "presets.json") _fps = max(1.0, float(os.environ.get("LED_SIM_FPS", "30"))) _px_period = 1.0 / _fps _pixels = None _pixels_dirty = False _last_px = 0.0 _jobs = [] # [due, fn, args] _in_job = False _flash_seen = {} _last_flash_check = 0.0 def _u8(data): arr = js.Uint8Array.new(len(data)) arr.assign(data) return arr def connected(): return True # ----- time --------------------------------------------------------------- def real_sleep(seconds): """Replacement for ``time.sleep``. Skipped inside deferred jobs (see defer).""" if _in_job or seconds <= 0: return js.simSleep(float(seconds) * 1000.0) # ----- radio -------------------------------------------------------------- def recv_nowait(): frame = js.simRecv() if frame is None: return (None, None) data = bytes(frame.to_bytes()) if len(data) < 6: return (None, None) return (data[:6], data[6:]) def recv(timeout_ms=0): host, msg = recv_nowait() if host is not None or timeout_ms == 0: return host, msg deadline = None if timeout_ms is None or timeout_ms < 0 else time.monotonic() + timeout_ms / 1000.0 while True: real_sleep(0.001) host, msg = recv_nowait() if host is not None: return host, msg if deadline is not None and time.monotonic() >= deadline: return (None, None) def pending(): return int(js.simPending()) def send_tx(dest_mac, packet): js.simTx(_u8(bytes(dest_mac) + bytes(packet))) # ----- pixels ------------------------------------------------------------- def _send_pixels(): global _pixels_dirty, _last_px _pixels_dirty = False _last_px = time.monotonic() js.simPixels(_u8(_pixels)) def push_pixels(buf): """``buf``: list of (r, g, b). Sent at most ``LED_SIM_FPS`` times a second.""" global _pixels, _pixels_dirty data = bytearray(len(buf) * 3) j = 0 for r, g, b in buf: data[j] = r data[j + 1] = g data[j + 2] = b j += 3 _pixels = bytes(data) _pixels_dirty = True if time.monotonic() - _last_px >= _px_period: _send_pixels() # ----- background work ---------------------------------------------------- def start_new_thread(fn, args, kwargs=None): """``_thread.start_new_thread`` stand-in: there are no threads in Pyodide. led-driver uses a thread only to answer pings after a random 50-500 ms delay. The job runs from the main loop after a delay in that range, with its own sleeps skipped so the strip keeps animating meanwhile. """ _jobs.append([time.monotonic() + random.uniform(0.05, 0.5), fn, tuple(args), kwargs or {}]) return len(_jobs) def _run_jobs(now): global _in_job if not _jobs: return due = [j for j in _jobs if j[0] <= now] if not due: return for j in due: _jobs.remove(j) _in_job = True try: j[1](*j[2], **j[3]) except Exception as e: # noqa: BLE001 print("sim job error:", e) finally: _in_job = False def _check_flash(now): global _last_flash_check if now - _last_flash_check < 1.0: return _last_flash_check = now for name in FLASH_FILES: try: with open(name, "r") as f: text = f.read() except OSError: continue if name not in _flash_seen: _flash_seen[name] = text continue if _flash_seen[name] != text: _flash_seen[name] = text js.simFlash(name, text) def on_feed(): now = time.monotonic() if _pixels_dirty and now - _last_px >= _px_period: _send_pixels() _run_jobs(now) _check_flash(now)