Files
nano-fcp/counter_control.py

188 lines
7.7 KiB
Python

"""
Internal lightweight HTTP control server for counter_live_rknn.
Exposes endpoints for starting, stopping, and checking manual batches.
"""
import json
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler
class ControlHandler(BaseHTTPRequestHandler):
def log_message(self, format, *args):
# Mute standard noisy HTTP console logs
pass
def do_GET(self):
if self.path in ("/status", "/api/status"):
status = self.server.store.get_status()
self._send_json(200, {"success": True, **status})
else:
self._send_json(404, {"success": False, "error": f"Endpoint {self.path} not found"})
def _read_json_body(self):
try:
length = int(self.headers.get("Content-Length", "0") or "0")
if length > 0:
raw = self.rfile.read(length).decode("utf-8")
return json.loads(raw) if raw else {}
except Exception:
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 (
"/start",
"/start/sack",
"/start/box",
"/api/start",
"/api/start/sack",
"/api/start/box",
"/api/batch/start",
"/api/batch/start/sack",
"/api/batch/start/box",
):
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)
sack_c = status.get("sack_count", 0)
box_c = status.get("box_count", 0)
self._send_json(200, {
"success": True,
"message": f"Batch #{status['batch_number']} is already running",
"batch_number": status["batch_number"],
"object_label": "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": body.get("plate") or status.get("plate"),
"status": "running",
})
else:
batch_num = self.server.store.start_new_batch()
if body:
if hasattr(self.server.store, "update_batch_metadata"):
self.server.store.update_batch_metadata(body)
elif hasattr(self.server.store, "current_state") and isinstance(self.server.store.current_state, dict):
plate = body.get("plate")
if plate:
self.server.store.current_state["plate"] = plate
if hasattr(self.server.store, "save_state"):
self.server.store.save_state()
self._send_json(200, {
"success": True,
"message": f"Started Batch #{batch_num}",
"batch_number": batch_num,
"object_label": "mixed",
"object_labels": ["sack", "box"],
"count": 0,
"sack_count": 0,
"box_count": 0,
"counts": {"sack": 0, "box": 0},
"plate": body.get("plate") or None,
"status": "running",
})
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,
"error": "No active batch to stop",
"status": "stopped",
})
else:
if body and hasattr(self.server.store, "update_batch_metadata"):
self.server.store.update_batch_metadata(body)
cur_num = status["batch_number"]
cur_count = status["count"]
cur_sack = status.get("sack_count", 0)
cur_box = status.get("box_count", 0)
cur_plate = body.get("plate") or status.get("plate")
ok = self.server.store.end_batch(closed_by="manual")
self._send_json(200, {
"success": True,
"message": f"Batch #{cur_num} stopped ({cur_count} items)",
"batch_number": cur_num,
"object_label": "mixed",
"object_labels": ["sack", "box"],
"count": cur_count,
"sack_count": cur_sack,
"box_count": cur_box,
"counts": {"sack": cur_sack, "box": cur_box},
"plate": cur_plate,
"persisted": ok,
"status": "stopped",
})
else:
self._send_json(404, {"success": False, "error": f"Endpoint {self.path} not found"})
def _send_json(self, code, payload):
data = json.dumps(payload, ensure_ascii=False).encode("utf-8")
self.send_response(code)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def start_control_server(store, host="127.0.0.1", port=5001, logger=print):
try:
server = HTTPServer((host, port), ControlHandler)
server.store = store
t = threading.Thread(target=server.serve_forever, daemon=True)
t.start()
logger(f"Internal control server listening on http://{host}:{port}")
return server
except Exception as e:
logger(f"Failed to start internal control server on {host}:{port}: {e}")
return None