Files
NODEDC_MISSION_CORE/src/k1link/fleet/rover_control.py
T

390 lines
21 KiB
Python

"""Ephemeral operator leases. No motor calls, command queue or persisted motion."""
from __future__ import annotations
import copy
import hashlib
import math
import secrets
import threading
import time
from .rover_diagnostics import RoverDiagnostics
from .rover_observation_evidence import ObservationEvidence
from .rover_telemetry_policy import DEFAULT_MS, telemetry_stop_ms
class RoverControl:
def __init__(self, clock=time.monotonic, diagnostic_root=None):
self.diagnostic_root = diagnostic_root
self.clock = clock
self.lock = threading.RLock()
self.changed = threading.Condition(self.lock)
self.boards = {}
self.network_changes = set()
self.clock_id = secrets.token_hex(16)
def _board(self, node):
if node not in self.boards:
self.boards[node]={"seen":-1e9,"watch":0,"snapshot":{},"session":None,"relay":None,"diagnostics":RoverDiagnostics(self.clock, self.diagnostic_root / hashlib.sha256(node.encode()).hexdigest()[:24] if self.diagnostic_root is not None else None),"observation":ObservationEvidence(self.clock)}
return self.boards[node]
def diagnostics(self,node,vehicle):
with self.lock:
board=self._board(node);value=board["diagnostics"];value.vehicle=vehicle
session=board["session"] or {}
value.context={"vehicle":vehicle,"core_clock_instance":self.clock_id,"driver_state":board["snapshot"].get("state"),
"session_id":session.get("id"),"settings":copy.deepcopy(session.get("settings")),
"telemetry_stop_ms":session.get("telemetry_stop_ms", DEFAULT_MS)}
return value
def forget(self, node):
"""A revoked/replaced binding cannot retain a lease or a fresh snapshot."""
with self.changed:
self.boards.pop(node, None)
self.changed.notify_all()
def observation(self, node, event=None):
with self.lock:
evidence = self._board(node)["observation"]
if event in ("operator_socket_opened", "operator_socket_closed"):
evidence.event(event)
return evidence.snapshot()
def view(self, node):
with self.lock:
b = self._board(node)
b["watch"] = self.clock() + 2
elapsed = max(0., self.clock() - b["seen"])
fresh = elapsed < 1
b["observation"].view(fresh)
self._expire(b)
control_fresh = b["session"] is not None and elapsed < self._telemetry_limit(b)
snapshot = copy.deepcopy(b["snapshot"]) if fresh or control_fresh else {}
for reading in snapshot.get("devices", []):
age = reading.get("age_ms")
if type(age) in (int, float) and math.isfinite(age):
reading["age_ms"] = max(0, age) + int(elapsed * 1000)
result = {"fresh": fresh, "snapshot": snapshot,
"controlling": b["session"] is not None,
"control_fresh": bool(control_fresh), "telemetry_age_ms": elapsed * 1000 if b["seen"] != -1e9 else None,
"telemetry_stop_ms": (b["session"] or {}).get("telemetry_stop_ms", DEFAULT_MS)}
if fresh and self.clock()-b.get("budget_seen", -1e9) < 2 and isinstance(b.get("link_budget"), dict):
result["link_budget"] = copy.deepcopy(b["link_budget"])
result["link_budget"]["snapshot_age_ms"] = max(0, int((self.clock()-b["budget_seen"])*1000))
return result
def _withdraw(self, b, reason, *, snapshot=None):
session = b["session"]
if session is None:
return
b["session"] = None
observed = b["snapshot"] if snapshot is None else snapshot
b["diagnostics"].control_stop.record(
reason, session, core_instance=self.clock_id,
telemetry_age_ms=(self.clock() - b["seen"]) * 1000,
driver_state=observed.get("state"),
)
def _expire(self, b):
if b["session"] and self.clock() >= b["session"]["until"]:
b["diagnostics"].trace.add("lease_expired", session_id=b["session"]["id"], sequence=b["session"]["sequence"])
self._withdraw(b, "input_deadline_expired")
@staticmethod
def _telemetry_limit(b):
return (b["session"] or {}).get("telemetry_stop_ms", DEFAULT_MS) / 1000
def disconnect(self, node, session):
"""A closed operator socket can retire only the lease it created."""
with self.changed:
b = self._board(node)
if b["session"] and b["session"]["id"] == session:
b["diagnostics"].trace.add("operator_disconnect", session_id=session)
self._withdraw(b, "operator_socket_closed")
self.changed.notify_all()
def network_change(self, node, active):
with self.lock:
if active:
board = self._board(node)
self._expire(board)
if board["session"] is not None:
raise ValueError("Отключите управление перед изменением сети борта.")
self.network_changes.add(node)
else:
self.network_changes.discard(node)
def arm(self, node, body, *, expires_at=None):
threshold = telemetry_stop_ms(body.get("telemetry_stop_ms", DEFAULT_MS))
body = {k:v for k,v in body.items() if k != "telemetry_stop_ms"}
duty = "max_duty_percent" in body
speed_key, low, high = ("max_duty_percent", 1, 100) if duty else ("max_erpm", 300, 3000)
if (set(body) != {"standstill_confirmed", "current_a", speed_key}
or body["standstill_confirmed"] is not True
or type(body["current_a"]) not in (int, float)
or not math.isfinite(body["current_a"]) or body["current_a"] < .5
or type(body[speed_key]) not in (int, float)
or not low <= body[speed_key] <= high):
raise ValueError("Подтвердите остановку и выберите допустимые пределы.")
with self.lock:
if node in self.network_changes:
raise ValueError("Дождитесь завершения переключения сети борта.")
b = self._board(node)
if expires_at is not None and self.clock() >= expires_at:
raise ValueError("Команда устарела до передачи на борт.")
self._expire(b)
if b["session"]:
raise ValueError("Аппаратом уже управляют. Сначала остановите управление.")
snapshot = b["snapshot"]
if self.clock() - b["seen"] >= 1 or snapshot.get("supported") is not True:
raise ValueError("Канал управления бортом недоступен.")
if duty and "duty" not in (snapshot.get("control_modes") or []):
raise ValueError("Обновите драйвер борта для управления газом.")
if snapshot.get("state") in ("preparing", "ready", "driving", "stopping"):
raise ValueError("Дождитесь завершения предыдущего управления.")
identifier = secrets.token_hex(16)
b["session"] = {"id": identifier, "sequence": 0, "operator_sequence": 0, "neutral_hold": False, "until": min(self.clock()+.4, expires_at) if expires_at is not None else self.clock()+.4,
"left": 0, "right": 0, "settings": copy.deepcopy(body), "telemetry_stop_ms": threshold}
self.changed.notify_all()
b["diagnostics"].trace.add("armed", session_id=identifier, settings=body, telemetry_stop_ms=threshold)
return {"session_id": identifier}
def command(self, node, body, *, expires_at=None):
if set(body) != {"session_id", "sequence", "left", "right", "stop"}:
raise ValueError("Некорректная команда управления.")
if (type(body["sequence"]) is not int or not 1 <= body["sequence"] < 2**53
or type(body["stop"]) is not bool
or any(type(body[k]) not in (int,float) or not math.isfinite(body[k])
or abs(body[k]) > 1 for k in ("left", "right"))):
raise ValueError("Некорректные значения команды.")
with self.lock:
b = self._board(node)
if expires_at is not None and self.clock() >= expires_at:
raise ValueError("Команда устарела до передачи на борт.")
self._expire(b)
s = b["session"]
if not s or not secrets.compare_digest(str(body["session_id"]), s["id"]):
raise ValueError("Управление завершено. Включите его заново.")
if body["sequence"] <= s["operator_sequence"]:
raise ValueError("Устаревшая команда отклонена.")
if body["stop"]:
self._withdraw(b, "operator_stop")
else:
s.update(sequence=max(s["sequence"]+1, body["sequence"]), operator_sequence=body["sequence"],
neutral_hold=False, left=body["left"], right=body["right"],
until=min(self.clock()+.4, expires_at) if expires_at is not None else self.clock()+.4)
self.changed.notify_all()
b["diagnostics"].trace.add("operator_command", **body)
return {"accepted_sequence": body["sequence"]}
def hold(self, node, body, *, expires_at=None):
"""Explicit socket-owner handoff to neutral; no remembered motion."""
if not isinstance(body, dict) or set(body) != {"session_id", "sequence"}:
raise ValueError("Некорректная команда удержания готовности.")
with self.lock:
result = self.command(node, {**body, "left": 0, "right": 0, "stop": False},
expires_at=expires_at)
self._board(node)["session"]["neutral_hold"] = True
return result
def maintain_neutral(self, node, session):
"""Called only by the live owner socket, never by observation/Node pull.
This creates fresh ZERO frames, not fresh timestamps on remembered
operator input. Missing a deadline is terminal even in neutral hold.
"""
with self.changed:
b = self._board(node)
self._expire(b)
s = b["session"]
if not s or s["id"] != session or not s["neutral_hold"]:
return False
snapshot = b["snapshot"]
if (self.clock()-b["seen"] >= self._telemetry_limit(b) or snapshot.get("supported") is not True
or (snapshot.get("session_id") == session and snapshot.get("state")
in ("stopping", "stopped", "fault", "receiver"))):
reason = ("telemetry_stale" if self.clock()-b["seen"] >= self._telemetry_limit(b) else
"driver_unavailable" if snapshot.get("supported") is not True else
"driver_terminal")
self._withdraw(b, reason)
self.changed.notify_all()
return False
s.update(left=0, right=0, sequence=s["sequence"]+1, until=self.clock()+.4)
self.changed.notify_all()
return True
@staticmethod
def _intent(session):
# Browser sequence and neutral ownership never cross the Node boundary.
return {key: copy.deepcopy(session[key]) for key in
("id", "sequence", "left", "right", "settings")}
def exchange(self, node, body):
"""Keep rejected authenticated observations diagnosable without publishing them."""
try:
return self._exchange(node, body)
except ValueError as error:
from .rover_rejection_evidence import rejection_evidence
with self.lock:
board = self.boards.get(node)
if board is not None:
evidence = rejection_evidence(error, body, self.clock_id, self.clock() * 1000)
board["observation"].reject(evidence)
board["diagnostics"].trace.local.add("node_observation_rejected", **evidence)
raise
def _exchange(self, node, body):
"""Called only after normal paired-certificate/binding authentication."""
snapshot = body.get("rover")
relay = body.get("relay_id")
observation_id = body.get("observation_id")
if observation_id is not None and (type(observation_id) is not int or not 0 < observation_id < 2**53):
raise ValueError("Invalid observation identity")
if not isinstance(snapshot, dict) or not isinstance(relay, str) or len(relay) != 32:
raise ValueError("Invalid rover exchange")
with self.lock:
observed = self.clock()
timing = body.get("sample_clock")
if timing is not None:
if (not isinstance(timing, dict) or set(timing) != {"instance", "monotonic_ms"}
or timing["instance"] != self.clock_id
or type(timing["monotonic_ms"]) not in (int, float)
or not math.isfinite(timing["monotonic_ms"])
or not 0 <= timing["monotonic_ms"] <= observed * 1000):
raise ValueError("Invalid rover sample clock")
observed = timing["monotonic_ms"] / 1000
b = self._board(node)
# A delayed/cancelled request may arrive after its replacement.
# It cannot replace a newer sample or change its relay/session.
publish = observed >= b["seen"]
metadata = None
if publish and "rover_details_v1" in body:
from .rover_metadata import expand
snapshot, metadata = expand(snapshot, body["rover_details_v1"], b.get("rover_metadata"),
relay=relay, observed=observed, now=self.clock())
if observation_id is not None:
b["diagnostics"].trace.local.add("node_observation_received", epoch=relay,
observation_id=observation_id, sample_core_mono_ms=observed*1000,
received_core_mono_ms=self.clock()*1000,
observation_age_ms=max(0, (self.clock()-observed)*1000), published=publish)
readings = snapshot.get("devices")
b["observation"].receive(observed, publish, len(readings) if isinstance(readings, list) else 0)
if publish and b["relay"] != relay:
self._withdraw(b, "relay_changed", snapshot=snapshot)
if publish and b["snapshot"].get("instance") != snapshot.get("instance"):
self._withdraw(b, "driver_restarted", snapshot=snapshot)
b["diagnostics"].ingest(body.get("diagnostics"))
if publish:
b["diagnostics"].supports_options=body.get("diagnostic_options_v1") is True
b["diagnostics"].supports_sources=body.get("diagnostic_sources_v1") is True
b["diagnostics"].supports_passive=body.get("diagnostic_passive_v1") is True
b.update(relay=relay, snapshot=copy.deepcopy(snapshot), seen=observed, rover_metadata=metadata)
if "link_budget" in body:
b["link_budget"] = copy.deepcopy(body["link_budget"])
b["budget_seen"] = observed
snapshot = b["snapshot"]
self._expire(b)
s = b["session"]
if s and snapshot.get("session_id") == s["id"] and snapshot.get("state") in (
"stopping", "stopped", "fault", "receiver"):
self._withdraw(b, "driver_terminal")
s = None
command = None
if s:
command = self._intent(s)
command["ttl_ms"] = max(0, min(400, int((s["until"]-self.clock())*1000)))
return {"watch": self.clock() < b["watch"] or s is not None or b["diagnostics"].watch_required(), "command": command,
"control_active": s is not None,
# Atomic hints only: never take the optional recorder/export
# locks in the command/telemetry path.
"diagnostics_pending": b["diagnostics"].traffic_pending(),
"control_clock": self._clock(), "diagnostics": None if body.get("diagnostic_lane_v1") is True else b["diagnostics"].desired(relay_ack=body.get("diagnostic_relay_ack_v1") is True)}
def exchange_diagnostics(self, node, body):
with self.lock:
diagnostics = self._board(node)["diagnostics"]
# No control lock while ingesting optional records or waiting for files.
return diagnostics.exchange(body)
def record_inventory(self, node, value):
with self.lock:
board = self.boards.get(node)
diagnostics = board["diagnostics"] if board else None
if diagnostics is not None:
diagnostics.record_inventory(value)
def record_telemetry_timing(self, node, dispatch_ms, reply_mono_ms):
"""DEV-only Core dispatch timing; no publication or lease renewal.
Excludes body transfer and reply transmission. Compare with Node's
HTTP trace to distinguish channel processing from end-to-end delay.
Aggregate at most once/second to avoid amplifying optional traffic.
Never retain the control lock while writing the diagnostic ring.
"""
with self.lock:
board = self.boards.get(node)
if board is None:
return
diagnostics = board["diagnostics"]
if not diagnostics.trace.recording():
board.pop("telemetry_timing", None)
return
trace = diagnostics.trace
now = self.clock()
timing = board.get("telemetry_timing")
if timing is None or timing["capture_id"] != trace.capture_identity():
timing = {"capture_id": trace.capture_identity(), "next": now, "count": 0, "max_ms": 0.}
board["telemetry_timing"] = timing
timing["count"] += 1
timing["max_ms"] = max(timing["max_ms"], dispatch_ms)
if now < timing["next"]:
return
details = {"exchanges": timing["count"],
"dispatch_max_ms": round(timing["max_ms"], 3),
"reply_mono_ms": reply_mono_ms}
timing.update(next=now + 1, count=0, max_ms=0.)
trace.add("node_telemetry_handled", **details)
def _clock(self):
return {"instance": self.clock_id, "monotonic_ms": self.clock()*1000}
def stream_trace(self, node):
"""Capture a recorder reference; never hold the authority lock on I/O."""
with self.lock:
board = self.boards.get(node)
return board["diagnostics"].trace if board else None
def intent_changed(self, node, relay, previous):
"""Read-only wake hint; never create a board or grant send authority."""
with self.lock:
board = self.boards.get(node)
current = (board["session"] if board and board["relay"] == relay else None) or {}
previous = previous or {}
return (current.get("id"), current.get("sequence")) != (
previous.get("id"), previous.get("sequence"))
def wait_for_intent(self, node, relay, previous, timeout=.05):
"""Wake on a new intent, including updates between write and wait."""
previous = previous or {}
def changed():
board = self._board(node)
current = (board["session"] if board["relay"] == relay else None) or {}
return (current.get("id"), current.get("sequence")) != (previous.get("id"), previous.get("sequence"))
with self.changed:
self.changed.wait_for(changed, timeout)
def stream(self, node, relay):
"""Latest intent only. Telemetry round trips never pace command delivery."""
with self.lock:
b = self._board(node)
self._expire(b)
if self.clock() - b["seen"] >= self._telemetry_limit(b):
self._withdraw(b, "telemetry_stale")
s = b["session"] if b["relay"] == relay else None
command = None
if s:
command = self._intent(s)
command["expires_mono_ms"] = s["until"]*1000
return {"watch": self.clock() < b["watch"] or s is not None or b["diagnostics"].watch_required(),
"command": command, "control_clock": self._clock()}