Ignore peer sync in auto mode and hold 30s batch timeout while truck is in zone
This commit is contained in:
1 parent
52612a4762
commit
581899e4a0
7 files changed
+321
-52
No files matched your search
+68
-37
@@ -121,7 +121,7 @@ class BatchStore:
|
||||
camera_name,
|
||||
object_label='sack',
|
||||
cutoff_time='06:00',
|
||||
batch_timeout=600.0,
|
||||
batch_timeout=30.0,
|
||||
min_object_per_batch=60,
|
||||
min_duration_per_batch=60,
|
||||
carry_ids=50,
|
||||
@@ -144,6 +144,7 @@ class BatchStore:
|
||||
|
||||
self.state_lock = threading.Lock()
|
||||
self.batch_timer = None
|
||||
self.truck_present = False
|
||||
self.previous_state = None
|
||||
self.shutdown_event = threading.Event()
|
||||
|
||||
@@ -262,35 +263,40 @@ class BatchStore:
|
||||
|
||||
def start_new_batch(self, counting_date=None, object_label=None):
|
||||
with self.state_lock:
|
||||
if self.current_state is not None:
|
||||
self.log(f'Batch #{self.current_state["batch_number"]} is already active')
|
||||
return self.current_state['batch_number']
|
||||
if counting_date is None:
|
||||
counting_date = self.get_counting_date()
|
||||
batch_number = self.get_next_batch_number(counting_date)
|
||||
now = datetime.now().isoformat()
|
||||
counted_ids = []
|
||||
if self.previous_state is not None:
|
||||
try:
|
||||
counted_ids = list(self.previous_state['counted_event_ids'][-self.carry_ids:])
|
||||
except (KeyError, TypeError):
|
||||
counted_ids = []
|
||||
self.current_state = {
|
||||
'counting_date': counting_date,
|
||||
'batch_number': batch_number,
|
||||
'object_label': 'mixed',
|
||||
'count': 0,
|
||||
'sack_count': 0,
|
||||
'box_count': 0,
|
||||
'start_time': now,
|
||||
'last_detection_time': now,
|
||||
'counted_event_ids': counted_ids,
|
||||
}
|
||||
self.save_state()
|
||||
if self.batch_mode != 'manual':
|
||||
self._reset_batch_timer()
|
||||
self.log(f'Started batch #{batch_number} for {counting_date} (mixed) [mode={self.batch_mode}]')
|
||||
return batch_number
|
||||
return self._start_new_batch_locked(
|
||||
counting_date=counting_date, object_label=object_label
|
||||
)
|
||||
|
||||
def _start_new_batch_locked(self, counting_date=None, object_label=None):
|
||||
if self.current_state is not None:
|
||||
self.log(f'Batch #{self.current_state["batch_number"]} is already active')
|
||||
return self.current_state['batch_number']
|
||||
if counting_date is None:
|
||||
counting_date = self.get_counting_date()
|
||||
batch_number = self.get_next_batch_number(counting_date)
|
||||
now = datetime.now().isoformat()
|
||||
counted_ids = []
|
||||
if self.previous_state is not None:
|
||||
try:
|
||||
counted_ids = list(self.previous_state['counted_event_ids'][-self.carry_ids:])
|
||||
except (KeyError, TypeError):
|
||||
counted_ids = []
|
||||
self.current_state = {
|
||||
'counting_date': counting_date,
|
||||
'batch_number': batch_number,
|
||||
'object_label': 'mixed',
|
||||
'count': 0,
|
||||
'sack_count': 0,
|
||||
'box_count': 0,
|
||||
'start_time': now,
|
||||
'last_detection_time': now,
|
||||
'counted_event_ids': counted_ids,
|
||||
}
|
||||
self.save_state()
|
||||
if self.batch_mode != 'manual':
|
||||
self._reset_batch_timer()
|
||||
self.log(f'Started batch #{batch_number} for {counting_date} (mixed) [mode={self.batch_mode}]')
|
||||
return batch_number
|
||||
|
||||
def update_batch_metadata(self, metadata):
|
||||
if not isinstance(metadata, dict):
|
||||
@@ -310,19 +316,43 @@ class BatchStore:
|
||||
self.current_state[key] = metadata[key]
|
||||
self.save_state()
|
||||
|
||||
def set_truck_present(self, present):
|
||||
"""Hold auto-mode batch timeout while a truck is present in the counting zone."""
|
||||
present = bool(present)
|
||||
with self.state_lock:
|
||||
was_present = self.truck_present
|
||||
self.truck_present = present
|
||||
if self.batch_mode == 'manual' or self.current_state is None:
|
||||
return
|
||||
if present:
|
||||
if self.batch_timer:
|
||||
self.batch_timer.cancel()
|
||||
self.batch_timer = None
|
||||
elif was_present or self.batch_timer is None:
|
||||
self._reset_batch_timer()
|
||||
|
||||
def _reset_batch_timer(self):
|
||||
if self.batch_timer:
|
||||
self.batch_timer.cancel()
|
||||
self.batch_timer = None
|
||||
if self.truck_present:
|
||||
return
|
||||
self.batch_timer = threading.Timer(self.batch_timeout, self._on_batch_timeout)
|
||||
self.batch_timer.daemon = True
|
||||
self.batch_timer.start()
|
||||
|
||||
def _on_batch_timeout(self):
|
||||
self.log(
|
||||
f'No {self.object_label} line crossing for {self.batch_timeout:.0f}s – '
|
||||
'closing batch (next crossing starts a new batch)'
|
||||
)
|
||||
self.end_batch(closed_by='timeout')
|
||||
with self.state_lock:
|
||||
if self.current_state is None:
|
||||
return
|
||||
if self.truck_present:
|
||||
self.batch_timer = None
|
||||
return
|
||||
self.log(
|
||||
f'No {self.object_label} line crossing for {self.batch_timeout:.0f}s '
|
||||
'and no truck in counting zone – closing batch (next crossing starts a new batch)'
|
||||
)
|
||||
self._end_batch_locked(closed_by='timeout')
|
||||
|
||||
def record_counted_object_crossing(self, track_id, object_label=None):
|
||||
"""Record one newly counted object crossing."""
|
||||
@@ -333,14 +363,14 @@ class BatchStore:
|
||||
if self.batch_mode == 'manual':
|
||||
# In manual mode, do not auto-start batch; wait for manual trigger
|
||||
return 0, False
|
||||
self.start_new_batch(counting_date, object_label=object_label)
|
||||
self._start_new_batch_locked(counting_date, object_label=object_label)
|
||||
started_new = True
|
||||
elif self.current_state['counting_date'] != counting_date:
|
||||
prev_label = self.current_state.get('object_label')
|
||||
self._end_batch_locked(closed_by='cutoff')
|
||||
if self.batch_mode == 'manual':
|
||||
return 0, False
|
||||
self.start_new_batch(counting_date, object_label=object_label or prev_label)
|
||||
self._start_new_batch_locked(counting_date, object_label=object_label or prev_label)
|
||||
started_new = True
|
||||
|
||||
item_label = self._normalize_item_label(object_label)
|
||||
@@ -601,6 +631,7 @@ class BatchStore:
|
||||
"plate": self.current_state.get('plate') if active else None,
|
||||
"source": self.current_state.get('source') if active else None,
|
||||
"fcp_batch_number": self.current_state.get('fcp_batch_number') if active else None,
|
||||
"truck_present": self.truck_present,
|
||||
}
|
||||
|
||||
def shutdown(self):
|
||||
|
||||
+4
-2
@@ -130,8 +130,10 @@ CUTOFF_TIME=06:00
|
||||
# Reset frame counter and ByteTrack track-ID counter back to 0 at daily cutoff
|
||||
RESET_COUNTERS_AT_CUTOFF=true
|
||||
|
||||
# Timeout in seconds without sack line crossings (disabled in manual mode so pauses won't close batch)
|
||||
BATCH_TIMEOUT_SECONDS=600
|
||||
# Timeout in seconds without line crossings before auto mode closes a batch.
|
||||
# While a truck is detected in the counting zone ROI, the timer is held; once no
|
||||
# truck is in the zone, the 30s countdown runs. (Disabled in manual mode.)
|
||||
BATCH_TIMEOUT_SECONDS=30
|
||||
|
||||
# Minimum sacks per batch to persist to database (set to 1 for manual mode)
|
||||
MIN_OBJECT_PER_BATCH=1
|
||||
|
||||
@@ -29,6 +29,44 @@ class ControlHandler(BaseHTTPRequestHandler):
|
||||
pass
|
||||
return {}
|
||||
|
||||
def _is_peer_sync_request(self, body):
|
||||
if self.headers.get("X-Peer-Sync", "").strip() == "1":
|
||||
return True
|
||||
if "X-API-Key" in self.headers:
|
||||
return True
|
||||
return isinstance(body, dict) and bool(body.get("source"))
|
||||
|
||||
def _get_batch_mode(self, status):
|
||||
mode = (
|
||||
getattr(self.server.store, "batch_mode", None)
|
||||
or status.get("batch_mode")
|
||||
or "manual"
|
||||
)
|
||||
return str(mode).strip().lower()
|
||||
|
||||
def _send_peer_ignored(self, action, status):
|
||||
sack_c = status.get("sack_count", 0)
|
||||
box_c = status.get("box_count", 0)
|
||||
payload = {
|
||||
"success": True,
|
||||
"ignored": True,
|
||||
"batch_mode": "auto",
|
||||
"message": f"Ignored peer {action}: counter is in auto mode",
|
||||
"batch_number": status.get("batch_number"),
|
||||
"object_label": status.get("object_label") or "mixed",
|
||||
"object_labels": ["sack", "box"],
|
||||
"count": status.get("count", 0),
|
||||
"sack_count": sack_c,
|
||||
"box_count": box_c,
|
||||
"counts": {"sack": sack_c, "box": box_c},
|
||||
"plate": status.get("plate"),
|
||||
"status": status.get("status")
|
||||
or ("running" if status.get("active") else "stopped"),
|
||||
}
|
||||
if action == "stop":
|
||||
payload["persisted"] = False
|
||||
self._send_json(200, payload)
|
||||
|
||||
def do_POST(self):
|
||||
clean_path = self.path.split("?", 1)[0].rstrip("/")
|
||||
if clean_path in (
|
||||
@@ -44,6 +82,9 @@ class ControlHandler(BaseHTTPRequestHandler):
|
||||
):
|
||||
body = self._read_json_body()
|
||||
status = self.server.store.get_status()
|
||||
if self._get_batch_mode(status) == "auto" and self._is_peer_sync_request(body):
|
||||
self._send_peer_ignored("start", status)
|
||||
return
|
||||
if status["active"]:
|
||||
if body and hasattr(self.server.store, "update_batch_metadata"):
|
||||
self.server.store.update_batch_metadata(body)
|
||||
@@ -89,6 +130,9 @@ class ControlHandler(BaseHTTPRequestHandler):
|
||||
elif clean_path in ("/stop", "/api/stop", "/api/batch/stop"):
|
||||
body = self._read_json_body()
|
||||
status = self.server.store.get_status()
|
||||
if self._get_batch_mode(status) == "auto" and self._is_peer_sync_request(body):
|
||||
self._send_peer_ignored("stop", status)
|
||||
return
|
||||
if not status["active"]:
|
||||
self._send_json(200, {
|
||||
"success": False,
|
||||
|
||||
+15
-12
@@ -137,9 +137,10 @@ def get_next_batch_number_db(counting_date=None):
|
||||
return 1
|
||||
|
||||
|
||||
def _send_counter_command(endpoint, data=b""):
|
||||
def _send_counter_command(endpoint, data=b"", headers=None):
|
||||
url = f"{COUNTER_CONTROL_URL}/{endpoint}"
|
||||
req = urllib.request.Request(url, data=data, method="POST")
|
||||
req_headers = dict(headers) if headers else {}
|
||||
req = urllib.request.Request(url, data=data, headers=req_headers, method="POST")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=4.0) as resp:
|
||||
return json.loads(resp.read().decode("utf-8")), resp.status
|
||||
@@ -310,11 +311,12 @@ def api_batch_start(object_label=None):
|
||||
if auth_err is not None:
|
||||
return auth_err
|
||||
raw = request.get_data()
|
||||
data, code = (
|
||||
_send_counter_command("start", data=raw)
|
||||
if raw
|
||||
else _send_counter_command("start")
|
||||
)
|
||||
kwargs = {}
|
||||
if raw:
|
||||
kwargs["data"] = raw
|
||||
if "X-API-Key" in request.headers:
|
||||
kwargs["headers"] = {"X-Peer-Sync": "1"}
|
||||
data, code = _send_counter_command("start", **kwargs)
|
||||
return jsonify(data), code
|
||||
|
||||
|
||||
@@ -324,11 +326,12 @@ def api_batch_stop():
|
||||
if auth_err is not None:
|
||||
return auth_err
|
||||
raw = request.get_data()
|
||||
data, code = (
|
||||
_send_counter_command("stop", data=raw)
|
||||
if raw
|
||||
else _send_counter_command("stop")
|
||||
)
|
||||
kwargs = {}
|
||||
if raw:
|
||||
kwargs["data"] = raw
|
||||
if "X-API-Key" in request.headers:
|
||||
kwargs["headers"] = {"X-Peer-Sync": "1"}
|
||||
data, code = _send_counter_command("stop", **kwargs)
|
||||
return jsonify(data), code
|
||||
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ DEDUP_FRAMES = int(os.getenv("DEDUP_FRAMES", "4"))
|
||||
DEDUP_PX = float(os.getenv("DEDUP_PX", "35"))
|
||||
|
||||
DAILY_CUTOFF_TIME = os.getenv("DAILY_CUTOFF_TIME", "06:00")
|
||||
BATCH_TIMEOUT_SECONDS = float(os.getenv("BATCH_TIMEOUT_SECONDS", "600"))
|
||||
BATCH_TIMEOUT_SECONDS = float(os.getenv("BATCH_TIMEOUT_SECONDS", "30"))
|
||||
MIN_OBJECT_PER_BATCH = int(os.getenv("MIN_OBJECT_PER_BATCH", "60"))
|
||||
MIN_DURATION_PER_BATCH = int(os.getenv("MIN_DURATION_PER_BATCH", "60"))
|
||||
BATCH_MODE = os.getenv("BATCH_MODE", "manual").strip().lower()
|
||||
@@ -1525,6 +1525,13 @@ def run():
|
||||
zone_x1, zone_x2 = manual_x1, manual_x2
|
||||
zone_source = "AUTO:MANUAL"
|
||||
|
||||
if not skip_inference:
|
||||
truck_in_zone = any(
|
||||
zone_x1 <= ((td["bbox"][0] + td["bbox"][2]) / 2.0) <= zone_x2
|
||||
for td in truck_dets
|
||||
)
|
||||
store.set_truck_present(truck_in_zone)
|
||||
|
||||
draw_counting_zone_x(frame, zone_x1, zone_x2, w, h, zone_source)
|
||||
|
||||
for tdet in truck_dets:
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import json
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
@@ -218,6 +219,93 @@ class BatchStoreUnifiedBatchTests(unittest.TestCase):
|
||||
)
|
||||
store.db.close()
|
||||
|
||||
def test_default_batch_timeout_is_30_seconds(self):
|
||||
store = self.make_store()
|
||||
self.addCleanup(store.db.close)
|
||||
self.assertEqual(store.batch_timeout, 30.0)
|
||||
|
||||
def test_auto_mode_truck_present_prevents_timeout_until_truck_leaves(self):
|
||||
store = batch_store.BatchStore(
|
||||
db_path=self.db_path,
|
||||
state_file=self.state_path,
|
||||
camera_name="camera-a",
|
||||
cutoff_time="23:59",
|
||||
batch_timeout=0.15,
|
||||
min_object_per_batch=1,
|
||||
min_duration_per_batch=0,
|
||||
batch_mode="auto",
|
||||
logger=lambda _message: None,
|
||||
)
|
||||
self.addCleanup(store.shutdown)
|
||||
|
||||
store.set_truck_present(True)
|
||||
store.record_counted_object_crossing(1, object_label="sack")
|
||||
time.sleep(0.25)
|
||||
|
||||
self.assertTrue(store.get_status()["active"])
|
||||
self.assertEqual(
|
||||
store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0], 0
|
||||
)
|
||||
|
||||
store.set_truck_present(False)
|
||||
time.sleep(0.25)
|
||||
|
||||
self.assertFalse(store.get_status()["active"])
|
||||
self.assertEqual(
|
||||
store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0], 1
|
||||
)
|
||||
|
||||
def test_auto_mode_truck_entering_cancels_running_timeout(self):
|
||||
store = batch_store.BatchStore(
|
||||
db_path=self.db_path,
|
||||
state_file=self.state_path,
|
||||
camera_name="camera-a",
|
||||
cutoff_time="23:59",
|
||||
batch_timeout=0.15,
|
||||
min_object_per_batch=1,
|
||||
min_duration_per_batch=0,
|
||||
batch_mode="auto",
|
||||
logger=lambda _message: None,
|
||||
)
|
||||
self.addCleanup(store.shutdown)
|
||||
|
||||
store.record_counted_object_crossing(1, object_label="sack")
|
||||
time.sleep(0.05)
|
||||
store.set_truck_present(True)
|
||||
time.sleep(0.20)
|
||||
|
||||
self.assertTrue(store.get_status()["active"])
|
||||
|
||||
store.set_truck_present(False)
|
||||
time.sleep(0.25)
|
||||
|
||||
self.assertFalse(store.get_status()["active"])
|
||||
self.assertEqual(
|
||||
store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0], 1
|
||||
)
|
||||
|
||||
def test_auto_mode_closes_after_timeout_when_no_truck(self):
|
||||
store = batch_store.BatchStore(
|
||||
db_path=self.db_path,
|
||||
state_file=self.state_path,
|
||||
camera_name="camera-a",
|
||||
cutoff_time="23:59",
|
||||
batch_timeout=0.15,
|
||||
min_object_per_batch=1,
|
||||
min_duration_per_batch=0,
|
||||
batch_mode="auto",
|
||||
logger=lambda _message: None,
|
||||
)
|
||||
self.addCleanup(store.shutdown)
|
||||
|
||||
store.record_counted_object_crossing(1, object_label="sack")
|
||||
time.sleep(0.25)
|
||||
|
||||
self.assertFalse(store.get_status()["active"])
|
||||
self.assertEqual(
|
||||
store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0], 1
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -15,6 +15,7 @@ TEST_ROOT = Path(tempfile.mkdtemp(prefix="feedmill-dashboard-", dir="/tmp/openco
|
||||
os.environ["DB_PATH"] = str(TEST_ROOT / "import.db")
|
||||
os.environ["STATE_FILE"] = str(TEST_ROOT / "import-state.json")
|
||||
|
||||
import batch_store
|
||||
import counter_dashboard
|
||||
from counter_control import start_control_server
|
||||
|
||||
@@ -322,6 +323,99 @@ class DashboardUnifiedBatchTests(unittest.TestCase):
|
||||
self.assertEqual(send.call_count, 1)
|
||||
self.assertEqual(send.call_args[0][0], "start")
|
||||
self.assertIn(b"B 1234 XYZ", send.call_args[1]["data"])
|
||||
self.assertEqual(send.call_args[1]["headers"], {"X-Peer-Sync": "1"})
|
||||
|
||||
def test_peer_sync_forwards_peer_header_on_start_and_stop(self):
|
||||
with patch("counter_dashboard._get_peer_api_token", return_value="secret-token"):
|
||||
for endpoint, action in (("/api/batch/start", "start"), ("/api/batch/stop", "stop")):
|
||||
with self.subTest(endpoint=endpoint, peer=True):
|
||||
with patch(
|
||||
"counter_dashboard._send_counter_command",
|
||||
return_value=({"success": True}, 200),
|
||||
) as send:
|
||||
resp = self.client.post(
|
||||
endpoint,
|
||||
headers={"X-API-Key": "secret-token"},
|
||||
json={"source": "fcp-semarang"},
|
||||
)
|
||||
self.assertEqual(resp.status_code, 200)
|
||||
self.assertEqual(send.call_args[0][0], action)
|
||||
self.assertEqual(send.call_args[1]["headers"], {"X-Peer-Sync": "1"})
|
||||
|
||||
with self.subTest(endpoint=endpoint, peer=False):
|
||||
with patch(
|
||||
"counter_dashboard._send_counter_command",
|
||||
return_value=({"success": True}, 200),
|
||||
) as send:
|
||||
resp = self.client.post(endpoint)
|
||||
self.assertEqual(resp.status_code, 200)
|
||||
send.assert_called_once_with(action)
|
||||
|
||||
def test_peer_sync_ignored_in_auto_mode_while_local_stop_works(self):
|
||||
store = batch_store.BatchStore(
|
||||
db_path=self.db_path,
|
||||
state_file=self.state_path,
|
||||
camera_name="camera-a",
|
||||
cutoff_time="23:59",
|
||||
batch_timeout=60.0,
|
||||
min_object_per_batch=1,
|
||||
min_duration_per_batch=0,
|
||||
batch_mode="auto",
|
||||
logger=lambda _message: None,
|
||||
)
|
||||
self.addCleanup(store.shutdown)
|
||||
server = start_control_server(store, host="127.0.0.1", port=0)
|
||||
self.addCleanup(server.server_close)
|
||||
self.addCleanup(server.shutdown)
|
||||
port = server.server_address[1]
|
||||
|
||||
def post(path, payload=None, peer=False):
|
||||
raw = json.dumps(payload).encode("utf-8") if payload is not None else b""
|
||||
headers = {"Content-Type": "application/json"} if payload is not None else {}
|
||||
if peer:
|
||||
headers["X-Peer-Sync"] = "1"
|
||||
req = urllib.request.Request(
|
||||
f"http://127.0.0.1:{port}{path}",
|
||||
data=raw,
|
||||
headers=headers,
|
||||
method="POST",
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=2) as resp:
|
||||
return resp.status, json.loads(resp.read().decode("utf-8"))
|
||||
|
||||
code, start_res = post(
|
||||
"/api/batch/start",
|
||||
payload={"source": "fcp-semarang", "plate": "B 1234 XYZ"},
|
||||
peer=True,
|
||||
)
|
||||
self.assertEqual(code, 200)
|
||||
self.assertTrue(start_res["success"])
|
||||
self.assertTrue(start_res["ignored"])
|
||||
self.assertEqual(start_res["object_labels"], ["sack", "box"])
|
||||
self.assertFalse(store.get_status()["active"])
|
||||
|
||||
store.record_counted_object_crossing(1, object_label="sack")
|
||||
self.assertTrue(store.get_status()["active"])
|
||||
|
||||
code, stop_res = post(
|
||||
"/api/batch/stop",
|
||||
payload={"source": "fcp-semarang"},
|
||||
peer=True,
|
||||
)
|
||||
self.assertEqual(code, 200)
|
||||
self.assertTrue(stop_res["success"])
|
||||
self.assertTrue(stop_res["ignored"])
|
||||
self.assertEqual(stop_res["object_labels"], ["sack", "box"])
|
||||
self.assertTrue(store.get_status()["active"])
|
||||
|
||||
code, local_stop = post("/api/batch/stop", payload=None, peer=False)
|
||||
self.assertEqual(code, 200)
|
||||
self.assertTrue(local_stop["success"])
|
||||
self.assertFalse(local_stop.get("ignored", False))
|
||||
self.assertFalse(store.get_status()["active"])
|
||||
self.assertEqual(
|
||||
store.db.execute("SELECT COUNT(*) FROM batches").fetchone()[0], 1
|
||||
)
|
||||
|
||||
|
||||
def tearDownModule():
|
||||
|
||||
Reference in new issue
Block a user