370 lines
13 KiB
Python
370 lines
13 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
flicker_watch.py — Continuous LP capture during video on/off cycles.
|
|
|
|
Operator watches the display. Script keeps cycling the video stream on/off
|
|
and triggering LP captures in the background. Files accumulate on the scope
|
|
without being transferred (fast).
|
|
|
|
Keys (no Enter needed):
|
|
f — flicker observed: transfer + archive + analyse recent captures
|
|
g — good baseline: transfer + archive recent captures (no analysis)
|
|
q — quit
|
|
|
|
Captures are organised under data/flicker/{event_ts}/ or data/good/{event_ts}/.
|
|
"""
|
|
|
|
import json
|
|
import select
|
|
import shutil
|
|
import sys
|
|
import termios
|
|
import time
|
|
import tty
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
import requests
|
|
import vxi11
|
|
|
|
import ai_mgmt
|
|
from csv_preprocessor import analyze_lp_file
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Config
|
|
# ---------------------------------------------------------------------------
|
|
SCOPE_IP = "192.168.45.4"
|
|
DEVICE_BASE = "http://192.168.45.8:5000"
|
|
VIDEO_URL = f"{DEVICE_BASE}/video"
|
|
|
|
DATA_DIR = Path(__file__).parent / "data"
|
|
FLICKER_DIR = DATA_DIR / "flicker"
|
|
GOOD_DIR = DATA_DIR / "good"
|
|
|
|
# LP capture parameters (matched to mipi_test_interactive.py)
|
|
LP_SCALE = 1e-6 # 1 µs/div → 20 µs window
|
|
LP_POINTS = 200_000
|
|
LP_TRIG_OFFSET = 9e-6 # 1 µs pre / 19 µs post-trigger
|
|
LP_V_SCALE = 0.2
|
|
LP_V_OFFSET = 0.6
|
|
LP_TRIG_LEVEL = 0.6
|
|
|
|
CYCLE_S = 10.0 # seconds video is on per cycle
|
|
TRIG_TIMEOUT_S = 2.0 # per-capture trigger wait
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Scope setup
|
|
# ---------------------------------------------------------------------------
|
|
scope = vxi11.Instrument(SCOPE_IP)
|
|
scope.timeout = 30
|
|
|
|
|
|
def setup_scope() -> None:
|
|
"""One-shot scope init — channels, math, default trigger."""
|
|
print("CONFIGURING SCOPE...")
|
|
cmds = [
|
|
"*RST", ":RUN", ":STOP",
|
|
":CHANnel1:DISPlay ON", ":CHANnel1:INPut DC50", ":CHANnel1:PROBe 19.2",
|
|
":CHANnel1:LABel 'CLK+'",
|
|
":CHANnel2:DISPlay ON", ":CHANnel2:INPut DC50", ":CHANnel2:PROBe 19.2",
|
|
":CHANnel2:LABel 'CLK-'",
|
|
":CHANnel3:DISPlay ON", ":CHANnel3:INPut DC50", ":CHANnel3:PROBe 19.2",
|
|
":CHANnel3:LABel 'DAT0+'",
|
|
":CHANnel4:DISPlay ON", ":CHANnel4:INPut DC50", ":CHANnel4:PROBe 19.2",
|
|
":CHANnel4:LABel 'DAT0-'",
|
|
":TIMebase:REFerence CENTer",
|
|
":TRIGger:MODE EDGE",
|
|
":ACQuire:MODE RTIMe", ":ACQuire:INTerpolate ON",
|
|
":DISPlay:LAYout STACKED",
|
|
]
|
|
for c in cmds:
|
|
scope.write(c)
|
|
time.sleep(0.05)
|
|
print("SCOPE READY.")
|
|
|
|
|
|
def configure_for_lp() -> None:
|
|
"""LP-mode: widen vertical range, falling-edge trigger on Ch3."""
|
|
for ch in (1, 2, 3, 4):
|
|
scope.write(f":CHANnel{ch}:SCALe {LP_V_SCALE:.3f}")
|
|
scope.write(f":CHANnel{ch}:OFFSet {LP_V_OFFSET:.3f}")
|
|
scope.write(":TRIGger:EDGE:SOURce CHANnel3")
|
|
scope.write(":TRIGger:EDGE:SLOPe NEGative")
|
|
scope.write(f":TRIGger:EDGE:LEVel {LP_TRIG_LEVEL:.3f}")
|
|
scope.write(":TRIGger:SWEep NORMal")
|
|
scope.write(f":TIMebase:SCALe {LP_SCALE:.3E}")
|
|
scope.write(f":ACQuire:POINts {LP_POINTS}")
|
|
scope.write(f":TIMebase:POSition {LP_TRIG_OFFSET:.2E}")
|
|
time.sleep(0.3)
|
|
|
|
|
|
def arm_and_wait(timeout_s: float) -> bool:
|
|
""":DIGitize + *OPC?. Returns True if trigger fired within timeout."""
|
|
global scope
|
|
prev = scope.timeout
|
|
try:
|
|
scope.timeout = timeout_s + 2
|
|
scope.write(":DIGitize")
|
|
return scope.ask("*OPC?").strip() == "1"
|
|
except Exception:
|
|
# Trigger timed out or scope locked up — reconnect.
|
|
try:
|
|
scope.close()
|
|
except Exception:
|
|
pass
|
|
time.sleep(1.0)
|
|
scope = vxi11.Instrument(SCOPE_IP)
|
|
scope.timeout = 30
|
|
try:
|
|
scope.write(":STOP")
|
|
except Exception:
|
|
pass
|
|
return False
|
|
finally:
|
|
try:
|
|
scope.timeout = prev
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def save_lp(base_name: str) -> None:
|
|
"""Save Ch1 (CLK+) and Ch3 (DAT0+) as CSV to scope's C:\\TEMP\\."""
|
|
base = f"C:\\TEMP\\{base_name}"
|
|
scope.write(f':DISK:SAVE:WAVeform CHANnel1,"{base}_clk.csv",CSV')
|
|
time.sleep(2.5)
|
|
scope.write(f':DISK:SAVE:WAVeform CHANnel3,"{base}_dat.csv",CSV')
|
|
time.sleep(2.5)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Non-blocking keyboard
|
|
# ---------------------------------------------------------------------------
|
|
class KeyReader:
|
|
def __enter__(self):
|
|
self.fd = sys.stdin.fileno()
|
|
self.old = termios.tcgetattr(self.fd)
|
|
tty.setcbreak(self.fd)
|
|
return self
|
|
|
|
def get_key(self) -> str | None:
|
|
if select.select([sys.stdin], [], [], 0)[0]:
|
|
return sys.stdin.read(1).lower()
|
|
return None
|
|
|
|
def __exit__(self, *_):
|
|
termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Video control
|
|
# ---------------------------------------------------------------------------
|
|
def video_start() -> None:
|
|
try:
|
|
requests.put(VIDEO_URL,
|
|
json={"action": "start", "mode": "static-pink"},
|
|
timeout=3)
|
|
except requests.exceptions.RequestException as e:
|
|
print(f" VIDEO START failed: {e}")
|
|
|
|
|
|
def video_stop() -> None:
|
|
try:
|
|
requests.put(VIDEO_URL, json={"action": "stop"}, timeout=3)
|
|
except requests.exceptions.RequestException as e:
|
|
print(f" VIDEO STOP failed: {e}")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Register snapshot from device (DSIM PHY + SN65DSI83)
|
|
# ---------------------------------------------------------------------------
|
|
def fetch_registers_snapshot(target_dir: Path, event_ts: str) -> None:
|
|
"""GET /registers + /sn65_registers, print key indicators, save JSON."""
|
|
combined: dict = {}
|
|
for endpoint, key in [("/registers", "dsim"),
|
|
("/sn65_registers", "sn65")]:
|
|
try:
|
|
r = requests.get(f"{DEVICE_BASE}{endpoint}", timeout=5)
|
|
r.raise_for_status()
|
|
combined[key] = r.json()
|
|
except Exception as e:
|
|
print(f" REGISTERS: {endpoint} failed — {e}")
|
|
combined[key] = None
|
|
|
|
# Quick-look indicators
|
|
sn65 = combined.get("sn65") or {}
|
|
regs = sn65.get("registers", {}) if isinstance(sn65, dict) else {}
|
|
csr_0a = regs.get("csr_0a", {}) or {}
|
|
csr_e5 = regs.get("csr_e5", {}) or {}
|
|
|
|
if csr_0a:
|
|
pll_str = "LOCKED" if csr_0a.get("pll_lock") else "*** UNLOCKED ***"
|
|
clk_str = "detected" if csr_0a.get("clk_det") else "NOT detected"
|
|
print(f" SN65: PLL {pll_str} CLK {clk_str} (CSR 0x0A = {csr_0a.get('value')})")
|
|
|
|
if csr_e5:
|
|
flags = [
|
|
("pll_unlock", "PLL_UNLOCK"),
|
|
("cha_sot_bit_err", "SOT_BIT_ERR"),
|
|
("cha_llp_err", "LLP_ERR"),
|
|
("cha_ecc_err", "ECC_ERR"),
|
|
("cha_lp_err", "LP_ERR"),
|
|
("cha_crc_err", "CRC_ERR"),
|
|
]
|
|
active = [label for k, label in flags if csr_e5.get(k)]
|
|
if active:
|
|
print(f" SN65: *** ERROR FLAGS: {', '.join(active)} "
|
|
f"(CSR 0xE5 = {csr_e5.get('value')}) ***")
|
|
else:
|
|
print(f" SN65: no error flags (CSR 0xE5 = {csr_e5.get('value')})")
|
|
|
|
out = target_dir / f"{event_ts}_registers.json"
|
|
try:
|
|
out.write_text(json.dumps(combined, indent=2))
|
|
print(f" registers → {out.relative_to(DATA_DIR.parent)}")
|
|
except Exception as e:
|
|
print(f" REGISTERS save failed: {e}")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Event handling: archive recent captures and (for flicker) analyse
|
|
# ---------------------------------------------------------------------------
|
|
def archive_and_analyse(event: str, since_iso: str) -> None:
|
|
"""
|
|
Pull every CSV from the scope, move into data/{event}/{event_ts}/.
|
|
For flicker events, run csv_preprocessor on each LP capture and print a
|
|
summary table. Always pulls a register snapshot from the device too.
|
|
"""
|
|
event_ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
target = (FLICKER_DIR if event == "flicker" else GOOD_DIR) / event_ts
|
|
target.mkdir(parents=True, exist_ok=True)
|
|
|
|
print(f"\n *** {event.upper()} EVENT @ {event_ts} ***")
|
|
|
|
# Register snapshot first (fast, before scope transfer which takes longer)
|
|
fetch_registers_snapshot(target, event_ts)
|
|
|
|
print(f" Transferring scope → {target} ...")
|
|
try:
|
|
copied, failed = ai_mgmt.transfer_csv_files()
|
|
except Exception as e:
|
|
print(f" TRANSFER ERROR: {e}")
|
|
return
|
|
print(f" {copied} file(s) transferred ({failed} failed)")
|
|
|
|
# Move just-arrived CSVs out of data/ (flat) into the event folder.
|
|
moved = 0
|
|
for csv in DATA_DIR.glob("*.csv"):
|
|
if csv.is_file():
|
|
shutil.move(str(csv), target / csv.name)
|
|
moved += 1
|
|
print(f" {moved} file(s) archived to {target.relative_to(DATA_DIR.parent)}")
|
|
|
|
if event != "flicker":
|
|
return
|
|
|
|
# Analyse the LP captures we just archived.
|
|
print("\n LP analysis (csv_preprocessor):")
|
|
print(" " + "-" * 78)
|
|
print(f" {'file':<46} {'lp_low_ns':>10} {'hs_amp_mV':>10} {'flicker?':>9}")
|
|
print(" " + "-" * 78)
|
|
|
|
lp_files = sorted(target.glob("*_lp_*_dat.csv"))
|
|
for f in lp_files:
|
|
try:
|
|
m = analyze_lp_file(f)
|
|
lp_low = getattr(m, "lp_low_duration_ns", None)
|
|
hs_amp = getattr(m, "hs_amp_mV", None)
|
|
sus = getattr(m, "flicker_suspect", False)
|
|
print(f" {f.name:<46} "
|
|
f"{(f'{lp_low:.1f}' if lp_low is not None else '?'):>10} "
|
|
f"{(f'{hs_amp:.1f}' if hs_amp is not None else '?'):>10} "
|
|
f"{('YES' if sus else 'no'):>9}")
|
|
except Exception as e:
|
|
print(f" {f.name:<46} ERROR: {e}")
|
|
print(" " + "-" * 78)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Main loop
|
|
# ---------------------------------------------------------------------------
|
|
def main() -> None:
|
|
DATA_DIR.mkdir(exist_ok=True)
|
|
FLICKER_DIR.mkdir(exist_ok=True)
|
|
GOOD_DIR.mkdir(exist_ok=True)
|
|
|
|
setup_scope()
|
|
configure_for_lp()
|
|
|
|
print("\n" + "=" * 64)
|
|
print(" FLICKER WATCH — keys: f=flicker g=good q=quit")
|
|
print("=" * 64 + "\n")
|
|
|
|
cycle = 0
|
|
try:
|
|
with KeyReader() as keys:
|
|
while True:
|
|
cycle += 1
|
|
cycle_ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
cycle_caps = []
|
|
cycle_end = time.time() + CYCLE_S
|
|
|
|
video_start()
|
|
print(f"\n[cycle {cycle:03d} {cycle_ts}] video ON "
|
|
f"({CYCLE_S:.0f}s window)", flush=True)
|
|
|
|
event = None
|
|
last_tick = 0.0
|
|
while time.time() < cycle_end:
|
|
seq = len(cycle_caps) + 1
|
|
base = f"{cycle_ts}_lp_c{cycle:03d}_{seq:02d}"
|
|
remaining = lambda: max(0, cycle_end - time.time())
|
|
|
|
if arm_and_wait(TRIG_TIMEOUT_S):
|
|
try:
|
|
save_lp(base)
|
|
cycle_caps.append(base)
|
|
print(f" + cap {seq:02d} [{remaining():4.1f}s left]",
|
|
flush=True)
|
|
except Exception as e:
|
|
print(f" save error: {e}", flush=True)
|
|
else:
|
|
# Trigger timed out — print a heartbeat at most every 2s
|
|
if time.time() - last_tick > 2.0:
|
|
print(f" ... waiting for trigger "
|
|
f"[{remaining():4.1f}s left]", flush=True)
|
|
last_tick = time.time()
|
|
|
|
key = keys.get_key()
|
|
if key in ("f", "g", "q"):
|
|
event = key
|
|
break
|
|
|
|
video_stop()
|
|
if event is None:
|
|
print(f"[cycle {cycle:03d}] ended "
|
|
f"({len(cycle_caps)} cap(s), no event)",
|
|
flush=True)
|
|
|
|
if event == "f":
|
|
archive_and_analyse("flicker", cycle_ts)
|
|
elif event == "g":
|
|
archive_and_analyse("good", cycle_ts)
|
|
elif event == "q":
|
|
print("\nQUIT requested.")
|
|
break
|
|
|
|
# Brief pause before next cycle so video stop settles.
|
|
time.sleep(0.5)
|
|
|
|
except KeyboardInterrupt:
|
|
print("\nInterrupted (Ctrl+C).")
|
|
finally:
|
|
try:
|
|
video_stop()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|