From 9cf6ea752738314e5de23695c21d8da2a8caf278 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Mon, 18 May 2026 20:34:27 +0100 Subject: [PATCH] Add active illumination pulse control --- docs/sensor-fusion-architecture.md | 14 ++- .../sensor_fusion/active_illumination.py | 114 ++++++++++++++++++ requirements-calibration.txt | 1 + scripts/pulse_tuya_light.py | 61 ++++++++++ state/map.yaml | 9 +- tests/test_sensor_fusion.py | 31 +++++ 6 files changed, 222 insertions(+), 8 deletions(-) create mode 100644 localcast/sensor_fusion/active_illumination.py create mode 100644 scripts/pulse_tuya_light.py diff --git a/docs/sensor-fusion-architecture.md b/docs/sensor-fusion-architecture.md index 7adacf0..6e9d01a 100644 --- a/docs/sensor-fusion-architecture.md +++ b/docs/sensor-fusion-architecture.md @@ -62,6 +62,7 @@ flowchart TD - `localcast.sensor_fusion.adapters` owns driver-facing frame ingress. Its first concrete adapter is an FFmpeg raw BGR reader for the PS3 Eye DirectShow path. - `localcast.sensor_fusion.camera_control` owns measurement-quality policy: luminance, clipping, contrast, and sharpness in; normalized exposure/gain/focus commands out. Driver adapters own translating those commands to OpenCV, DirectShow, vendor tools, or no-op mocks. - `localcast.sensor_fusion.dense_stereo` owns a debug CPU reference for dense calibrated RGB surface claims. It is useful for tests and shader parity, but the live million-splat path belongs to Aquarium/GPU compute. +- `localcast.sensor_fusion.active_illumination` owns deliberate light pulses as calibration telemetry. A Tuya bulb is an optional local-network actuator, not a rendering authority; its pulse timestamps are evidence for camera exposure/depth response. - `localcast.sensor_fusion.render_bridge` owns the in-process render-frame ABI: cached point claims plus target dimensions, Spout sender name, source timestamp range, intended visual presentation time, and ambisonic/audio alignment time. - `localcast.sensor_fusion.cultcache_docs` owns the typed CultCache document boundary for live visual state. - `localcast.sensor_fusion.spout_output` owns the deadline OBS publication sink: render-frame packet in, GPU texture plus Spout sender heartbeat out. @@ -147,12 +148,13 @@ That lets the final stream compositor buffer point-cloud visuals until they alig 1. Load real ChArUco intrinsics/extrinsics into `config/sensor-fusion.json`; the current dense Kiyo pair geometry is provisional and should not be mistaken for truth. 2. Move dense matching from CPU block search to GPU-resident stereo/flow so the million-sample target is not murdered by Python loops. -3. Add detector adapters that turn PS3 Eye frames into `Observation2D` marker detections. -4. Record an observation run from the two PS3 Eyes into typed CultCache docs. -5. Feed `RenderFramePacket` into Aquarium Engine. -6. Add Aquarium-side GPU point/brush rendering to a D3D render target. -7. Publish the render target as a Spout2 sender and receive it in OBS. -8. Replace compatibility JSON render-frame paths once no deadline script depends on them. +3. If a Tuya light is available on the local network, run `scripts/pulse_tuya_light.py` with its local key and align pulse timestamps against camera brightness response. +4. Add detector adapters that turn PS3 Eye frames into `Observation2D` marker detections. +5. Record an observation run from the two PS3 Eyes into typed CultCache docs. +6. Feed `RenderFramePacket` into Aquarium Engine. +7. Add Aquarium-side GPU point/brush rendering to a D3D render target. +8. Publish the render target as a Spout2 sender and receive it in OBS. +9. Replace compatibility JSON render-frame paths once no deadline script depends on them. ## References diff --git a/localcast/sensor_fusion/active_illumination.py b/localcast/sensor_fusion/active_illumination.py new file mode 100644 index 0000000..cd1ceb0 --- /dev/null +++ b/localcast/sensor_fusion/active_illumination.py @@ -0,0 +1,114 @@ +from __future__ import annotations + +from dataclasses import dataclass +import time +from typing import Protocol + + +class LightPort(Protocol): + def set_white(self, *, brightness_percent: int, color_temp_percent: int) -> None: + ... + + +@dataclass(frozen=True) +class IlluminationPulse: + pulse_index: int + start_monotonic_ns: int + bright_until_monotonic_ns: int + settle_until_monotonic_ns: int + brightness_percent: int + color_temp_percent: int + + +@dataclass(frozen=True) +class IlluminationPulsePlan: + pulse_count: int = 6 + bright_ms: int = 90 + settle_ms: int = 210 + brightness_percent: int = 100 + idle_brightness_percent: int = 18 + color_temp_percent: int = 50 + + @property + def period_ms(self) -> int: + return self.bright_ms + self.settle_ms + + +class ActiveIlluminationController: + def __init__(self, light: LightPort, plan: IlluminationPulsePlan): + self.light = light + self.plan = plan + + def run(self, *, sleep=time.sleep, clock_ns=time.monotonic_ns) -> tuple[IlluminationPulse, ...]: + pulses: list[IlluminationPulse] = [] + try: + for index in range(max(0, self.plan.pulse_count)): + start = clock_ns() + self.light.set_white( + brightness_percent=self.plan.brightness_percent, + color_temp_percent=self.plan.color_temp_percent, + ) + bright_until = start + self.plan.bright_ms * 1_000_000 + sleep(max(0.0, self.plan.bright_ms / 1000.0)) + self.light.set_white( + brightness_percent=self.plan.idle_brightness_percent, + color_temp_percent=self.plan.color_temp_percent, + ) + settle_until = bright_until + self.plan.settle_ms * 1_000_000 + pulses.append( + IlluminationPulse( + pulse_index=index, + start_monotonic_ns=start, + bright_until_monotonic_ns=bright_until, + settle_until_monotonic_ns=settle_until, + brightness_percent=self.plan.brightness_percent, + color_temp_percent=self.plan.color_temp_percent, + ) + ) + sleep(max(0.0, self.plan.settle_ms / 1000.0)) + finally: + self.light.set_white( + brightness_percent=self.plan.idle_brightness_percent, + color_temp_percent=self.plan.color_temp_percent, + ) + return tuple(pulses) + + +class TinytuyaLightPort: + def __init__( + self, + *, + device_id: str, + address: str, + local_key: str, + version: str = "3.3", + dps_power: str = "20", + dps_brightness: str = "22", + dps_color_temp: str = "23", + ) -> None: + import tinytuya + + self.device = tinytuya.BulbDevice(device_id, address, local_key) + self.device.set_version(float(version)) + self.dps_power = dps_power + self.dps_brightness = dps_brightness + self.dps_color_temp = dps_color_temp + + def set_white(self, *, brightness_percent: int, color_temp_percent: int) -> None: + brightness = _clamp_percent(brightness_percent) + color_temp = _clamp_percent(color_temp_percent) + if hasattr(self.device, "turn_on"): + self.device.turn_on() + self._set_value(self.dps_power, True) + self._set_value(self.dps_brightness, int(round(brightness * 10))) + self._set_value(self.dps_color_temp, int(round(color_temp * 10))) + + def _set_value(self, dps: str, value: object) -> None: + if hasattr(self.device, "set_value"): + self.device.set_value(dps, value) + return + raise RuntimeError("tinytuya device does not expose set_value") + + +def _clamp_percent(value: int) -> int: + return max(0, min(100, int(value))) diff --git a/requirements-calibration.txt b/requirements-calibration.txt index ea83dc9..6e0b1cd 100644 --- a/requirements-calibration.txt +++ b/requirements-calibration.txt @@ -1,4 +1,5 @@ opencv-contrib-python +tinytuya sounddevice soundcard scipy diff --git a/scripts/pulse_tuya_light.py b/scripts/pulse_tuya_light.py new file mode 100644 index 0000000..d6f2d95 --- /dev/null +++ b/scripts/pulse_tuya_light.py @@ -0,0 +1,61 @@ +import argparse +from pathlib import Path +import sys + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) + +from localcast.sensor_fusion.active_illumination import ( + ActiveIlluminationController, + IlluminationPulsePlan, + TinytuyaLightPort, +) + + +def main() -> None: + parser = argparse.ArgumentParser(description="Pulse a local Tuya light as active vision calibration telemetry.") + parser.add_argument("--device-id", required=True) + parser.add_argument("--address", required=True) + parser.add_argument("--local-key", required=True) + parser.add_argument("--version", default="3.3") + parser.add_argument("--count", type=int, default=6) + parser.add_argument("--bright-ms", type=int, default=90) + parser.add_argument("--settle-ms", type=int, default=210) + parser.add_argument("--brightness", type=int, default=100) + parser.add_argument("--idle-brightness", type=int, default=18) + parser.add_argument("--color-temp", type=int, default=50) + parser.add_argument("--dps-power", default="20") + parser.add_argument("--dps-brightness", default="22") + parser.add_argument("--dps-color-temp", default="23") + args = parser.parse_args() + + light = TinytuyaLightPort( + device_id=args.device_id, + address=args.address, + local_key=args.local_key, + version=args.version, + dps_power=args.dps_power, + dps_brightness=args.dps_brightness, + dps_color_temp=args.dps_color_temp, + ) + plan = IlluminationPulsePlan( + pulse_count=args.count, + bright_ms=args.bright_ms, + settle_ms=args.settle_ms, + brightness_percent=args.brightness, + idle_brightness_percent=args.idle_brightness, + color_temp_percent=args.color_temp, + ) + pulses = ActiveIlluminationController(light, plan).run() + for pulse in pulses: + print( + f"pulse={pulse.pulse_index} " + f"start_ns={pulse.start_monotonic_ns} " + f"bright_until_ns={pulse.bright_until_monotonic_ns} " + f"settle_until_ns={pulse.settle_until_monotonic_ns}" + ) + + +if __name__ == "__main__": + main() diff --git a/state/map.yaml b/state/map.yaml index 7f6e1a2..b828a7e 100644 --- a/state/map.yaml +++ b/state/map.yaml @@ -228,7 +228,10 @@ current_status: compute rather than Python loops. A separate adaptive camera-control policy measures luminance, clipping, contrast, and sharpness, then emits normalized exposure/gain/focus commands through the - OpenCV capture adapter when the driver accepts them. Unit tests inject + OpenCV capture adapter when the driver accepts them. Active illumination now + has an optional Tuya local-network pulse hook for deliberately modulating + room light as calibration telemetry; pulse timestamps can be aligned against + camera brightness/depth response. Unit tests inject synthetic cameras and frames so the core does not depend on live camera drivers. next_action: > @@ -237,7 +240,9 @@ current_status: local `config/sensor-fusion.json`, then move the dense RGB stereo matcher to a GPU-resident stereo/flow pass so high-detail surface claims can scale toward the million-splat temporal accumulator without Python owning each - point. Then replace the synthetic live producer with a detector adapter that + point. If a Tuya light is available, run the local-key pulse hook and record + its timestamps against camera responses as active illumination evidence. + Then replace the synthetic live producer with a detector adapter that turns FFmpeg PS3 Eye frames into marker `Observation2D` records for the fusion core and publishes the same typed CultCache/CultNet render-frame document. In parallel, move the render-frame consumer into Aquarium Engine so diff --git a/tests/test_sensor_fusion.py b/tests/test_sensor_fusion.py index 83cc038..7bea9e1 100644 --- a/tests/test_sensor_fusion.py +++ b/tests/test_sensor_fusion.py @@ -35,6 +35,7 @@ from scripts.live_sensor_fusion import ( rgb_room_splats, unpack_leap_packed_channels, ) +from localcast.sensor_fusion.active_illumination import ActiveIlluminationController, IlluminationPulsePlan from audio_field.cultcache_audio import make_audio_source_events, make_spatial_audio_frame from localcast.sensor_fusion.adapters import read_raw_bgr_frames @@ -332,6 +333,36 @@ class SensorFusionTests(unittest.TestCase): self.assertTrue(all(point.stable_key.startswith("leap-motion:green") for point in points)) self.assertTrue(all(point.source_timestamp_ns == 456 for point in points)) + def test_active_illumination_pulse_plan_emits_timed_brightness_changes(self): + class FakeLight: + def __init__(self): + self.calls = [] + + def set_white(self, *, brightness_percent, color_temp_percent): + self.calls.append((brightness_percent, color_temp_percent)) + + ticks = iter([1_000_000_000, 1_300_000_000]) + light = FakeLight() + controller = ActiveIlluminationController( + light, + IlluminationPulsePlan( + pulse_count=2, + bright_ms=10, + settle_ms=20, + brightness_percent=91, + idle_brightness_percent=17, + color_temp_percent=44, + ), + ) + + pulses = controller.run(sleep=lambda _: None, clock_ns=lambda: next(ticks)) + + self.assertEqual(2, len(pulses)) + self.assertEqual((91, 44), light.calls[0]) + self.assertEqual((17, 44), light.calls[1]) + self.assertEqual((17, 44), light.calls[-1]) + self.assertEqual(1_010_000_000, pulses[0].bright_until_monotonic_ns) + def test_adaptive_camera_controller_reduces_overexposure(self): controller = AdaptiveCameraController(target=CameraQualityTarget(mean_luma=0.5, luma_deadband=0.02))