ce10c741fc
A standalone prototype of passage confirmation, tried on park-lab against the real lane, relays and barrier (wiki: concepts/zone-anpr-poc.md). - zone_anpr.py: vehicle detection on the camera stream, a drawn zone and crossing line, and the zone flow: nothing is decided while the zone is busy; when it is free the last crossing decides (A -> B passed, otherwise abandoned -> close relay). Relays follow read-then-fire with an online probe and a check before every datagram; disarmed by default. Plates are read from hi-res stills and stream frames into one consensus. - test_flow.py: 65 offline checks of the flow, the relay rules against a mock board, and the plate reads. No camera, model or relay needed. - recordings/ + replay_recordings.py: the followed car's boxes for 48 real entry visits of 2026-11-21/22, replayed through the judging code. - trial_report.py: per-visit report of a drive, run on park-lab. The detector model, local config and outputs are not committed (.gitignore). Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RZgP5oZdzvo92Eouc9eRv5
569 lines
27 KiB
Python
569 lines
27 KiB
Python
#!/usr/bin/env python3
|
|
"""Offline checks of the PoC's flow and relay rules. No camera, no model, no real relay board:
|
|
the detector is a script and the Dingtian board is a mock on 127.0.0.1.
|
|
|
|
../../apps/vision/.venv/bin/python test_flow.py
|
|
|
|
Part 1 drives Camera.step() with scripted boxes on the zone/line below and checks the verdict
|
|
and the relay requests. Part 2 runs the real Relays class against the mock board and checks
|
|
every datagram it sends. Part 3 wires a real Camera to the real Relays and the mock board, armed
|
|
and with the close live, and checks what reaches the board. Part 4 checks the plate reads: the
|
|
stream frames as the first source, the hi-res still as the second."""
|
|
from __future__ import annotations
|
|
|
|
import socket
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import numpy as np
|
|
|
|
sys.path.insert(0, str(Path(__file__).parent))
|
|
import zone_anpr as z # noqa: E402
|
|
|
|
W, H = 1280, 720
|
|
# The entry camera's zone and line as they were on park-lab on 2026-11-22.
|
|
ENTRY = dict(name="entry",
|
|
zone=[[0.6844, 0.7045], [0.1531, 0.873], [0.1708, 0.9952], [0.9396, 0.9896], [0.9521, 0.7508]],
|
|
line=dict(p1=dict(x=0.8497, y=1.0), p2=dict(x=0.91, y=0.7505), direction="a-to-b"))
|
|
LOG: list[str] = []
|
|
z.log = lambda *a: LOG.append(" ".join(str(x) for x in a))
|
|
OUT = Path(tempfile.mkdtemp(prefix="zone-anpr-test-"))
|
|
FAILED = []
|
|
|
|
|
|
def check(name, cond, detail=""):
|
|
print((" ok " if cond else " FAIL ") + name + (f" [{detail}]" if detail and not cond else ""))
|
|
if not cond:
|
|
FAILED.append(name)
|
|
|
|
|
|
# ============================================================================ part 1: the flow
|
|
class Det:
|
|
now: list = []
|
|
|
|
def detect(self, img):
|
|
return list(self.now)
|
|
|
|
|
|
class RelStub:
|
|
def __init__(self):
|
|
self.asked = [] # (kind, channel, valid)
|
|
|
|
def pulse(self, kind, ch, why, valid=None):
|
|
self.asked.append((kind, ch, valid))
|
|
|
|
@property
|
|
def kinds(self):
|
|
return [k for k, _, _ in self.asked]
|
|
|
|
|
|
class StubApp:
|
|
def __init__(self, **cfg):
|
|
self.cfg = dict(detect_fps=5, min_plate_conf=0.9, votes_needed=3, agree_share=0.75, visit_gap_s=3,
|
|
zone_overlap=0.2, start_conf=0.4, zone_free_s=1, clip_keep=0)
|
|
self.cfg.update(cfg)
|
|
self.out = OUT
|
|
(OUT / "saves").mkdir(parents=True, exist_ok=True)
|
|
(OUT / "visits.jsonl").unlink(missing_ok=True)
|
|
self.io_lock, self.lane_lock = threading.Lock(), threading.Lock()
|
|
self.relays, self.yolox = RelStub(), Det()
|
|
self.cam = z.Camera(dict(ENTRY, url="rtsp://x", relay_open=1, relay_close=2), self)
|
|
self.cam.read_busy = True # no plate reads
|
|
self.cams = [self.cam]
|
|
self.t = 1_000_000.0
|
|
|
|
def tick(self, *boxes, n=1):
|
|
for _ in range(n):
|
|
self.t += 0.2
|
|
self.yolox.now = list(boxes)
|
|
self.cam.step(np.zeros((H, W, 3), np.uint8), self.t)
|
|
|
|
def drive(self, xs, **kw):
|
|
for cx in xs:
|
|
self.tick(car(cx, **kw))
|
|
|
|
def verdicts(self):
|
|
import json
|
|
p = OUT / "visits.jsonl"
|
|
return [json.loads(x) for x in p.read_text().splitlines()] if p.exists() else []
|
|
|
|
|
|
def car(cx, bottom=0.95, w=0.34, h=0.36, conf=0.8):
|
|
return ((cx - w / 2) * W, (bottom - h) * H, (cx + w / 2) * W, bottom * H, conf, 2)
|
|
|
|
|
|
APPROACH = (0.10, 0.20, 0.30, 0.40, 0.50) # side A, into the zone, up to the line
|
|
BACK_OUT = (0.40, 0.30, 0.20, 0.10, 0.02, -0.05, -0.10, -0.10, -0.10, -0.10, -0.10, -0.10) # still in view, out of the zone
|
|
THROUGH = (0.60, 0.70, 0.80, 0.90, 1.00, 1.08, 1.14) # over the line, out of the picture on side B
|
|
|
|
|
|
def flow_tests():
|
|
print("flow")
|
|
a = StubApp()
|
|
a.drive(APPROACH); a.drive(THROUGH); a.tick(n=16)
|
|
v = a.verdicts()
|
|
check("drive through: passed, no close", len(v) == 1 and v[0]["verdict"] == "passed" and v[0]["last_crossing"] == "a-to-b"
|
|
and a.relays.kinds == ["open"], f"{v} {a.relays.kinds}")
|
|
|
|
a = StubApp()
|
|
a.drive(APPROACH); a.drive(BACK_OUT)
|
|
v = a.verdicts()
|
|
check("stops short of the line, reverses out: abandoned (no crossing), close", len(v) == 1 and v[0]["verdict"] == "abandoned"
|
|
and v[0]["last_crossing"] is None and v[0]["end"] == "left_zone" and a.relays.kinds == ["open", "close"], f"{v} {a.relays.kinds}")
|
|
|
|
a = StubApp()
|
|
a.drive(APPROACH); a.drive((0.60, 0.70, 0.70, 0.60, 0.50)); a.drive(BACK_OUT)
|
|
v = a.verdicts()
|
|
check("nose over the line, reverses out: abandoned, close", len(v) == 1 and v[0]["verdict"] == "abandoned"
|
|
and "line" in [p["side"] for p in v[0]["path"]] and a.relays.kinds == ["open", "close"], f"{v} {a.relays.kinds}")
|
|
|
|
a = StubApp()
|
|
a.drive(APPROACH); a.drive((0.60, 0.72, 0.84, 0.96, 1.10, 1.10)) # fully over (rear past the line), held: A → B
|
|
a.drive((0.96, 0.84, 0.72, 0.60, 0.50)); a.drive(BACK_OUT) # and fully back: B → A
|
|
v = a.verdicts()
|
|
check("A → B, then B → A: the LAST crossing counts: abandoned, close", len(v) == 1 and v[0]["verdict"] == "abandoned"
|
|
and [c["crossing"] for c in v[0]["crossings"]] == ["a-to-b", "b-to-a"] and a.relays.kinds == ["open", "close"], f"{v} {a.relays.kinds}")
|
|
|
|
a = StubApp()
|
|
a.drive((1.10, 1.06, 0.96, 0.84, 0.72, 0.60, 0.50)); a.drive(BACK_OUT) # comes from side B, leaves on A
|
|
v = a.verdicts()
|
|
check("drive-out (B → A): abandoned, close", len(v) == 1 and v[0]["verdict"] == "abandoned" and v[0]["last_crossing"] == "b-to-a"
|
|
and a.relays.kinds == ["open", "close"], f"{v} {a.relays.kinds}")
|
|
|
|
# ---- one stray box must not decide (the night of 2026-11-22: a crossing judged abandoned)
|
|
a = StubApp()
|
|
a.drive(APPROACH); a.drive((0.60, 0.70, 0.80, 0.90, 1.00)) # on the line, driving through, box at the right edge
|
|
a.tick((0.22 * W, 0.34 * H, 0.67 * W, 0.84 * H, 0.8, 2)) # ONE last box on the blur: side A, outside the zone
|
|
a.tick(n=20)
|
|
v = a.verdicts()
|
|
check("a pass whose LAST box is a stray one on side A is still passed, no close", len(v) == 1 and v[0]["verdict"] == "passed"
|
|
and v[0]["path"][-1]["side"] == "line" and a.relays.kinds == ["open"], f"{v} {a.relays.kinds}")
|
|
|
|
a = StubApp()
|
|
a.drive(APPROACH); a.tick(car(0.50), n=3) # standing on side A, short of the line
|
|
a.tick((0.23 * W, 0.56 * H, 0.998 * W, 0.99 * H, 0.8, 2)) # ONE look: stretched to the right edge, driving off
|
|
a.tick(n=20)
|
|
v = a.verdicts()
|
|
check("a fast pass seen for ONE last look at the picture's edge is passed, no close", len(v) == 1 and v[0]["verdict"] == "passed"
|
|
and [p["side"] for p in v[0]["path"]] == ["a", "line"] and a.relays.kinds == ["open"], f"{v} {a.relays.kinds}")
|
|
|
|
a = StubApp()
|
|
a.drive(APPROACH); a.tick(car(0.50), n=3)
|
|
a.tick(car(0.50, bottom=0.60)) # ONE look with the box above the zone, then nothing
|
|
a.tick(n=20)
|
|
v = a.verdicts()
|
|
check("one look outside the zone is not 'seen leaving': unclear, no close", len(v) == 1 and v[0]["verdict"] == "unclear"
|
|
and v[0]["end"] == "lost" and a.relays.kinds == ["open"], f"{v} {a.relays.kinds}")
|
|
|
|
a = StubApp()
|
|
a.drive(APPROACH); a.drive((0.60, 0.70)) # on the line
|
|
a.tick(car(1.10)) # ONE look fully on B, then back on the line
|
|
a.drive((0.70, 0.60, 0.50)); a.drive(BACK_OUT)
|
|
v = a.verdicts()
|
|
check("a side seen for one look only is not a crossing", len(v) == 1 and v[0]["crossings"] == [] and v[0]["verdict"] == "abandoned", str(v))
|
|
|
|
a = StubApp()
|
|
a.drive(APPROACH); a.tick(n=20) # standing in the zone, then simply not detected any more
|
|
v = a.verdicts()
|
|
check("vanishes INSIDE the zone: unclear, NO close", len(v) == 1 and v[0]["verdict"] == "unclear" and v[0]["end"] == "lost"
|
|
and a.relays.kinds == ["open"], f"{v} {a.relays.kinds}")
|
|
|
|
a = StubApp()
|
|
a.tick(car(0.25, bottom=0.97, w=0.5, h=0.3), n=3); a.tick(n=20) # in the zone, box touching the left edge, then not detected
|
|
v = a.verdicts()
|
|
check("vanishes in the zone with its box at the picture's edge: unclear, NO close", len(v) == 1 and v[0]["verdict"] == "unclear"
|
|
and v[0]["end"] == "left_view" and a.relays.kinds == ["open"], f"{v} {a.relays.kinds}")
|
|
|
|
a = StubApp(close_on_lost=True)
|
|
a.drive(APPROACH); a.tick(n=20)
|
|
v = a.verdicts()
|
|
check("the same with close_on_lost: abandoned, close", len(v) == 1 and v[0]["verdict"] == "abandoned" and a.relays.kinds == ["open", "close"])
|
|
|
|
a = StubApp()
|
|
a.drive(APPROACH); a.tick(n=10); a.tick(car(0.50), n=3) # lost for 2 s, seen again in the same place
|
|
check("a 2 s detection gap does not end the visit or open again", not a.verdicts() and a.relays.kinds == ["open"])
|
|
|
|
# the zone is BUSY with another vehicle: nothing is decided
|
|
a = StubApp()
|
|
a.drive(APPROACH)
|
|
other = (0.80 * W, 0.62 * H, 1.0 * W, 0.97 * H, 0.8, 2) # a second vehicle in the zone, beyond the line
|
|
for cx in BACK_OUT + (-0.10,) * 20:
|
|
a.tick(car(cx), other)
|
|
check("car 1 reverses out, car 2 still in the zone: NO decision, no close", not a.verdicts() and a.relays.kinds == ["open"],
|
|
f"{a.verdicts()} {a.relays.kinds}")
|
|
a.tick(n=20)
|
|
v = a.verdicts()
|
|
check("... decided only once the zone is free", len(v) == 1 and v[0]["verdict"] == "abandoned" and a.relays.kinds == ["open", "close"],
|
|
f"{v} {a.relays.kinds}")
|
|
|
|
# the close is checked again right before it is sent
|
|
a = StubApp()
|
|
a.drive(APPROACH); a.drive(BACK_OUT)
|
|
valid = a.relays.asked[-1][2]
|
|
check("close is valid while the zone stays free", a.relays.kinds[-1] == "close" and valid() is True)
|
|
a.tick(car(0.45, conf=0.2)) # a weak detection in the zone: below the start threshold, no new visit
|
|
check("... and NOT valid once any vehicle is back in the zone", a.cam.track is None and valid() is False)
|
|
a.tick()
|
|
check("... valid again when the zone is free", valid() is True)
|
|
a.cam.checked_t -= 5
|
|
check("... and NOT valid on a stale picture (no frame for > 1 s)", valid() is False)
|
|
a = StubApp()
|
|
a.drive(APPROACH); a.drive(BACK_OUT); valid = a.relays.asked[-1][2]
|
|
a.tick(car(0.45))
|
|
check("... and NOT valid once a new visit has started", a.cam.track is not None and valid() is False)
|
|
a = StubApp()
|
|
a.drive(APPROACH)
|
|
ov = a.relays.asked[0][2]
|
|
check("open is valid during its visit", ov() is True)
|
|
a.drive(BACK_OUT)
|
|
check("... and not after it", ov() is False)
|
|
|
|
|
|
# ============================================================================ part 2: the relay rules
|
|
class Board:
|
|
"""A Dingtian board on 127.0.0.1: answers the binary UDP protocol, and has a web port."""
|
|
|
|
def __init__(self):
|
|
self.udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
self.udp.bind(("127.0.0.1", 0))
|
|
self.port = self.udp.getsockname()[1]
|
|
self.tcp = socket.socket()
|
|
self.tcp.bind(("127.0.0.1", 0))
|
|
self.tcp.listen(8)
|
|
self.http_port = self.tcp.getsockname()[1]
|
|
self.relays = 0 # bit 0 = relay 1
|
|
self.stuck = 0 # bits that ignore an off command
|
|
self.answer = True
|
|
self.seen: list[str] = [] # 'read' | 'off1' | 'jog2' ...
|
|
threading.Thread(target=self.serve, daemon=True).start()
|
|
|
|
def serve(self):
|
|
while True:
|
|
d, addr = self.udp.recvfrom(64)
|
|
cmd = d[3]
|
|
if cmd == 0x00:
|
|
self.seen.append("read")
|
|
reply = bytes([0xFF, 0xAA, d[2], 0x00, self.relays, 0x0F])
|
|
elif cmd == 0x01:
|
|
mask, val = d[6], d[7]
|
|
self.seen.append("".join(f"{'on' if val >> i & 1 else 'off'}{i + 1}" for i in range(4) if mask >> i & 1))
|
|
self.relays = (self.relays & ~mask | val & mask) | self.stuck
|
|
reply = bytes([0xFF, 0xAA, d[2], 0x01])
|
|
elif cmd == 0x03:
|
|
ch = (d[6] >> 1) + 1
|
|
self.seen.append(f"jog{ch}")
|
|
reply = bytes([0xFF, 0xAA, d[2], 0x03])
|
|
else:
|
|
continue
|
|
if self.answer:
|
|
self.udp.sendto(reply, addr)
|
|
|
|
|
|
class RApp:
|
|
def __init__(self):
|
|
self.out = OUT
|
|
self.io_lock = threading.Lock()
|
|
|
|
|
|
def relays(board, close_live=True, armed=True):
|
|
(OUT / "relays.jsonl").unlink(missing_ok=True)
|
|
r = z.Relays(dict(host="127.0.0.1", port=board.port, http_port=board.http_port, close_live=close_live,
|
|
timeout_s=0.15, retry_s=0.02), RApp())
|
|
r.pair = {1: 2, 2: 1}
|
|
if armed:
|
|
r.arm(True)
|
|
return r
|
|
|
|
|
|
def last(n=1):
|
|
import json
|
|
p = OUT / "relays.jsonl"
|
|
rows = [json.loads(x) for x in p.read_text().splitlines()] if p.exists() else []
|
|
return rows[-n] if len(rows) >= n else {}
|
|
|
|
|
|
def wait(cond, s=3.0):
|
|
t = time.time()
|
|
while time.time() - t < s:
|
|
if cond():
|
|
return True
|
|
time.sleep(0.01)
|
|
return False
|
|
|
|
|
|
def relay_tests():
|
|
print("relays")
|
|
b = Board()
|
|
r = relays(b, armed=False)
|
|
r.pulse("open", 1, "t"); r.pulse("close", 2, "t"); time.sleep(0.3)
|
|
check("disarmed: nothing at all is sent to the board", b.seen == [] and last()["sent"] is False, str(b.seen))
|
|
|
|
b = Board(); r = relays(b, close_live=False)
|
|
r.pulse("close", 2, "t"); time.sleep(0.3)
|
|
check("armed, close_live off: a close sends nothing", b.seen == [], str(b.seen))
|
|
r.pulse("open", 1, "t")
|
|
check("armed: open = read, other relay off, fire", wait(lambda: last().get("sent")) and b.seen == ["read", "jog1"], str(b.seen))
|
|
|
|
b = Board(); r = relays(b)
|
|
r.pulse("close", 2, "t")
|
|
check("close live: read, R1 off, fire R2", wait(lambda: last().get("sent")) and b.seen == ["read", "jog2"], str(b.seen))
|
|
|
|
b = Board(); b.relays = 0b10; r = relays(b)
|
|
r.pulse("open", 1, "t")
|
|
check("open while R2 reads on: off command, read again, then fire", wait(lambda: last().get("sent"))
|
|
and b.seen == ["read", "off2", "read", "jog1"] and last()["other_was_on"] == 1, str(b.seen))
|
|
|
|
b = Board(); b.relays = 0b01; r = relays(b)
|
|
r.pulse("close", 2, "t")
|
|
check("close while R1 reads on: the same, the other way round", wait(lambda: last().get("sent"))
|
|
and b.seen == ["read", "off1", "read", "jog2"], str(b.seen))
|
|
|
|
b = Board(); b.relays = b.stuck = 0b10; r = relays(b)
|
|
r.pulse("open", 1, "first")
|
|
wait(lambda: b.seen.count("off2") >= 5)
|
|
check("other relay stays on: keeps trying, never fires", "jog1" not in b.seen and b.seen.count("off2") >= 5, str(b.seen[:8]))
|
|
b.stuck = b.relays = 0
|
|
check("... and fires as soon as it reads off", wait(lambda: last().get("sent")) and b.seen[-1] == "jog1", str(b.seen[-4:]))
|
|
|
|
b = Board(); b.relays = b.stuck = 0b01; r = relays(b)
|
|
r.pulse("close", 2, "stale close")
|
|
wait(lambda: b.seen.count("off1") >= 3) # the close is looping on a relay that will not switch off
|
|
r.pulse("open", 1, "new open")
|
|
b.relays = b.stuck = 0
|
|
ok = wait(lambda: last().get("sent") and last()["why"] == "new open")
|
|
check("a newer command replaces one that is still trying", ok and last(2).get("dropped") == "replaced by a newer command"
|
|
and "jog2" not in b.seen, f"{last(2)} {b.seen}")
|
|
|
|
b = Board(); b.relays = b.stuck = 0b01; r = relays(b)
|
|
r.pulse("close", 2, "t")
|
|
wait(lambda: b.seen.count("off1") >= 3)
|
|
r.arm(False)
|
|
check("disarmed while trying: dropped, nothing fired", wait(lambda: last().get("dropped") == "relays no longer armed") and "jog2" not in b.seen)
|
|
|
|
b = Board(); b.relays = b.stuck = 0b01; r = relays(b)
|
|
free = [True]
|
|
r.pulse("close", 2, "t", valid=lambda: free[0])
|
|
wait(lambda: b.seen.count("off1") >= 3)
|
|
free[0] = False
|
|
check("zone busy again while trying: the close is dropped", wait(lambda: "no longer valid" in last().get("dropped", "")) and "jog2" not in b.seen)
|
|
|
|
b = Board(); r = relays(b)
|
|
r.pulse("close", 2, "t", valid=lambda: False)
|
|
check("a close that is not valid sends nothing, not even a read", wait(lambda: last().get("dropped")) and b.seen == [], str(b.seen))
|
|
|
|
b = Board(); b.answer = False; r = relays(b)
|
|
r.pulse("open", 1, "t")
|
|
wait(lambda: b.seen.count("read") >= 4)
|
|
check("reads unanswered, controller online: keeps looping, not offline", r.offline is False and b.seen.count("read") >= 4 and "jog1" not in b.seen, str(b.seen))
|
|
b.answer = True
|
|
check("... and fires once the reads come back", wait(lambda: last().get("sent")) and b.seen[-1] == "jog1")
|
|
|
|
b = Board(); b.answer = False; r = relays(b)
|
|
r.online = lambda: False # nothing answers on the network
|
|
r.pulse("open", 1, "t")
|
|
check("read fails, controller not on the network: flagged OFFLINE, not sent", wait(lambda: last().get("error") == "relay controller offline")
|
|
and r.offline is True and last()["sent"] is False and "jog1" not in b.seen, f"{last()} {b.seen}")
|
|
b.answer = True; del r.online
|
|
r.pulse("open", 1, "t")
|
|
check("... the flag clears when the board answers again", wait(lambda: last().get("sent")) and r.offline is False)
|
|
|
|
b = Board(); r = relays(b)
|
|
check("online probe: web port open", r.online() is True)
|
|
b.tcp.close()
|
|
check("online probe: connection refused still means a board is there", r.online() is True)
|
|
st = relays(Board()).status()
|
|
check("status read for the page", st == dict(online=True, relays=[False, False, False, False]), str(st))
|
|
|
|
|
|
# ============================================================================ part 3: camera + relays + board
|
|
def joined(board):
|
|
"""A real Camera wired to the real Relays class, armed, with the close live."""
|
|
a = StubApp()
|
|
a.relays = relays(board)
|
|
return a
|
|
|
|
|
|
def joined_tests():
|
|
print("camera + relays + board")
|
|
b = Board(); a = joined(b)
|
|
a.drive(APPROACH)
|
|
check("visit starts: read, then R1 is fired", wait(lambda: b.seen == ["read", "jog1"]), str(b.seen))
|
|
a.drive(BACK_OUT)
|
|
check("turn-back: the LIVE close reaches the board (read, then R2)", wait(lambda: b.seen == ["read", "jog1", "read", "jog2"])
|
|
and last()["action"] == "close" and last()["sent"] is True, f"{b.seen} {last()}")
|
|
|
|
b = Board(); a = joined(b)
|
|
a.drive(APPROACH); a.drive(THROUGH); a.tick(n=16); time.sleep(0.3)
|
|
check("drive through: no close is sent", b.seen == ["read", "jog1"], str(b.seen))
|
|
|
|
b = Board(); a = joined(b)
|
|
a.drive(APPROACH); wait(lambda: "jog1" in b.seen)
|
|
b.relays = b.stuck = 0b01 # R1 keeps reading on, so the close has to keep trying
|
|
a.drive(BACK_OUT)
|
|
check("close is trying while R1 reads on", wait(lambda: b.seen.count("off1") >= 2) and "jog2" not in b.seen, str(b.seen))
|
|
a.tick(car(0.45, conf=0.2)) # a vehicle is back in the zone
|
|
ok = wait(lambda: "no longer valid" in last().get("dropped", ""))
|
|
b.relays = b.stuck = 0
|
|
time.sleep(0.3)
|
|
check("a vehicle back in the zone: the close is dropped, R2 never fires", ok and "jog2" not in b.seen, f"{last()} {b.seen}")
|
|
|
|
b = Board(); a = joined(b)
|
|
a.drive(APPROACH); wait(lambda: "jog1" in b.seen)
|
|
b.relays = b.stuck = 0b01
|
|
a.drive(BACK_OUT); wait(lambda: b.seen.count("off1") >= 2)
|
|
b.relays = b.stuck = 0
|
|
a.tick(car(0.45)) # a new car: a new visit, and its open replaces the close still trying
|
|
check("a new visit's open is not held up by a close", wait(lambda: last().get("sent") and last()["action"] == "open")
|
|
and "jog2" not in b.seen, f"{last()} {b.seen}")
|
|
|
|
b = Board(); a = joined(b)
|
|
a.drive(APPROACH); a.tick(n=20); time.sleep(0.3)
|
|
check("car vanishes inside the zone: no close is sent", b.seen == ["read", "jog1"], str(b.seen))
|
|
|
|
|
|
# ============================================================================ part 4: plate reads
|
|
class PlateReader:
|
|
"""Scripted plate reader. A crop of the (black) stream frame and a crop of the (white) still
|
|
are told apart by their brightness."""
|
|
|
|
def __init__(self, stream=("AA927AU", 0.99), still=("AA927AU", 0.99), plate_px=100):
|
|
self.answers = dict(stream=stream, still=still)
|
|
self.calls = dict(stream=0, still=0)
|
|
self.plate_px = plate_px # how wide the plate is in the picture
|
|
|
|
def read(self, img):
|
|
src = "still" if img.max() else "stream"
|
|
self.calls[src] += 1
|
|
a = self.answers[src]
|
|
return (a[0], a[1], (1, 1, 1 + self.plate_px, 21)) if a else None
|
|
|
|
|
|
def plates(reader, still=None, **cfg):
|
|
"""A camera that reads plates: from the stream, and from `still()` if given."""
|
|
a = StubApp(**cfg)
|
|
(OUT / "reads.jsonl").unlink(missing_ok=True)
|
|
a.reader = reader
|
|
a.cam.read_busy = False
|
|
if still:
|
|
a.cam.plate_snap_url = "http://camera/still"
|
|
a.cam.fetch_still = still
|
|
return a
|
|
|
|
|
|
def slow_drive(a, xs, pause=0.03):
|
|
for cx in xs:
|
|
a.tick(car(cx))
|
|
wait(lambda: not a.cam.read_busy, 1)
|
|
time.sleep(pause)
|
|
|
|
|
|
def last_read():
|
|
import json
|
|
p = OUT / "reads.jsonl"
|
|
rows = [json.loads(x) for x in p.read_text().splitlines()] if p.exists() else []
|
|
return rows[-1] if rows else {}
|
|
|
|
|
|
def plate_tests():
|
|
print("plate reads")
|
|
white = lambda: np.full((2160, 3840, 3), 200, np.uint8) # noqa: E731 (a still; bright, not burnt out)
|
|
burnt = lambda: np.full((2160, 3840, 3), 255, np.uint8) # noqa: E731 (a still burnt out all around the plate)
|
|
|
|
r = PlateReader(); a = plates(r)
|
|
slow_drive(a, APPROACH + (0.5,) * 6)
|
|
lr = last_read()
|
|
check("stream only: decided on the third frame, from the stream", lr.get("status") == "decided" and lr["plate"] == "AA927AU"
|
|
and lr["sources"]["stream"]["votes"] == 3 and lr["best_from"] == "stream" and lr["after_s"] is not None, str(lr))
|
|
check("... and nothing is read after the decision", r.calls["stream"] == 3, str(r.calls))
|
|
|
|
r = PlateReader(stream=("XX1", 0.3), still=("A927AU", 0.99)); a = plates(r, still=burnt, still_interval_s=0)
|
|
slow_drive(a, APPROACH + (0.5,) * 8)
|
|
wait(lambda: not a.cam.still_busy, 2)
|
|
check("a sure read with burnt-out pixels beside the plate does NOT vote", not a.cam.visit_done and a.cam.visit_votes == {}
|
|
and a.cam.visit_src["still"][1] >= 3, f"{a.cam.visit_votes} {a.cam.visit_src}")
|
|
img = np.full((60, 400, 3), 120, np.uint8)
|
|
check("plate_glare: nothing burnt beside the plate", z.plate_glare(img, (100, 20, 200, 40)) == 0.0)
|
|
img[20:40, 80:100] = 255 # a flare touching the plate's left end
|
|
check("plate_glare: a flare at the plate's left end", z.plate_glare(img, (100, 20, 200, 40)) >= 0.5)
|
|
img = np.full((60, 400, 3), 120, np.uint8); img[:, :40] = 255 # a flare well away from the plate
|
|
check("plate_glare: a flare away from the plate does not count", z.plate_glare(img, (100, 20, 200, 40)) == 0.0)
|
|
|
|
def slow_still():
|
|
time.sleep(0.4)
|
|
return white()
|
|
r = PlateReader(); a = plates(r, still=slow_still, still_interval_s=0)
|
|
slow_drive(a, APPROACH + (0.5,) * 6)
|
|
wait(lambda: not a.cam.still_busy, 2)
|
|
lr = last_read()
|
|
check("stream decides before a slow still comes back; the late still does not vote", lr.get("status") == "decided"
|
|
and lr["sources"]["stream"]["votes"] == 3 and lr["sources"]["still"]["votes"] == 0 and a.cam.visit_votes == {"AA927AU": 3},
|
|
f"{lr} {a.cam.visit_votes}")
|
|
|
|
r = PlateReader(plate_px=50); a = plates(r) # sure reads, but the plate is 50 px of 1280 wide
|
|
slow_drive(a, APPROACH + (0.5,) * 6)
|
|
check("stream reads of a small plate do not vote", not a.cam.visit_done and a.cam.visit_votes == {} and a.cam.visit_src["stream"][1] >= 5,
|
|
f"{a.cam.visit_votes} {a.cam.visit_src}")
|
|
|
|
r = PlateReader(stream=("AA927AU", 0.5)); a = plates(r, still=white, still_interval_s=0)
|
|
slow_drive(a, APPROACH + (0.5,) * 10)
|
|
wait(lambda: not a.cam.still_busy, 2)
|
|
lr = last_read()
|
|
check("stream reads unsure: the stills decide (the second source)", lr.get("status") == "decided" and lr["sources"]["still"]["votes"] == 3
|
|
and lr["sources"]["stream"]["votes"] == 0 and lr["best_from"] == "still", str(lr))
|
|
|
|
def broken():
|
|
raise OSError("503")
|
|
r = PlateReader(); a = plates(r, still=broken, still_interval_s=0)
|
|
slow_drive(a, APPROACH + (0.5,) * 6)
|
|
lr = last_read()
|
|
check("stills failing: backs off, the stream still decides", lr.get("status") == "decided" and a.cam.read_fails >= 1
|
|
and a.cam.read_pause_until > time.time() and a.cam.visit_src["still"][0] == 1, f"{lr} {a.cam.read_fails} {a.cam.visit_src}")
|
|
|
|
r = PlateReader(stream=("XX1", 0.3), still=("XX1", 0.3)); a = plates(r, still=white, still_interval_s=0, max_stream_reads=10, max_stills=3)
|
|
slow_drive(a, (0.5,) * 40, pause=0.01)
|
|
wait(lambda: not a.cam.still_busy, 2)
|
|
check("a car STANDING with an unreadable plate: reads stop at the caps", r.calls == dict(stream=10, still=3) and not a.cam.visit_done, str(r.calls))
|
|
slow_drive(a, (0.38,) * 15, pause=0.01) # it moves on: the caps start again
|
|
wait(lambda: not a.cam.still_busy, 2)
|
|
check("... the car moves: it is read again", r.calls == dict(stream=20, still=6), str(r.calls))
|
|
a.drive(BACK_OUT)
|
|
lr = last_read()
|
|
check("... and the visit is recorded as no_read, with its sources", lr.get("status") == "no_read" and lr["sources"]["stream"]["tries"] >= 20
|
|
and lr["sources"]["still"]["tries"] >= 6, str(lr))
|
|
|
|
r = PlateReader(stream=("XX1", 0.3), still=("XX1", 0.3)); a = plates(r, still=white, still_interval_s=0, max_stream_reads=5, max_stills=3)
|
|
slow_drive(a, tuple(0.30 + 0.004 * k for k in range(60)), pause=0.01) # creeping: 0.4% of the frame per look
|
|
check("a car CREEPING up slowly is read all the way, past the caps", r.calls["stream"] > 5 * 3, str(r.calls))
|
|
|
|
r = PlateReader(stream=("AA927XU", 0.99), still=("AA927AU", 0.99)); a = plates(r, still=white, still_interval_s=0)
|
|
slow_drive(a, APPROACH + (0.5,) * 12)
|
|
wait(lambda: not a.cam.still_busy, 2)
|
|
lr = last_read()
|
|
check("sure but WRONG stream votes do not block the stills: decided by the stills alone", lr.get("status") == "decided"
|
|
and lr["plate"] == "AA927AU" and lr["votes"].get("AA927XU", 0) >= 2, str(lr))
|
|
|
|
r = PlateReader(stream=("XX1", 0.3), still=("AA927AU", 0.5)); a = plates(r, still=white, still_interval_s=0, clip_keep=5, still_keep=2)
|
|
slow_drive(a, APPROACH + (0.5,) * 6)
|
|
wait(lambda: not a.cam.still_busy, 2)
|
|
clip = a.cam.track["clip"]
|
|
kept = sorted(x.name for x in clip.glob("still_*.jpg"))
|
|
check("every still's car crop is kept with its read, beside the visit's clip, up to still_keep",
|
|
kept == ["still_01_AA927AU_0.50.jpg", "still_02_AA927AU_0.50.jpg"] and len((clip / "stills.jsonl").read_text().splitlines()) == 2, str(kept))
|
|
|
|
r = PlateReader(stream=("XX1", 0.3), still=("XX1", 0.3)); a = plates(r, still=white, still_interval_s=0.5)
|
|
slow_drive(a, APPROACH + (0.5,) * 4, pause=0.01) # well under half a second in all
|
|
check("stills are paced: at most one per still_interval_s", a.cam.visit_src["still"][0] == 1 and a.cam.visit_src["stream"][0] >= 4,
|
|
str(a.cam.visit_src))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
flow_tests()
|
|
relay_tests()
|
|
joined_tests()
|
|
plate_tests()
|
|
print("\nFAILED: " + ", ".join(FAILED) if FAILED else "\nall passed")
|
|
sys.exit(1 if FAILED else 0)
|