feat(dev): correlate telemetry recovery, safety stops and passive drive evidence
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import math
|
||||
import secrets
|
||||
import threading
|
||||
@@ -9,10 +10,12 @@ 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):
|
||||
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)
|
||||
@@ -22,7 +25,7 @@ class RoverControl:
|
||||
|
||||
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),"observation":ObservationEvidence(self.clock)}
|
||||
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):
|
||||
@@ -30,7 +33,8 @@ class RoverControl:
|
||||
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"))}
|
||||
"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):
|
||||
@@ -54,13 +58,16 @@ class RoverControl:
|
||||
fresh = elapsed < 1
|
||||
b["observation"].view(fresh)
|
||||
self._expire(b)
|
||||
snapshot = copy.deepcopy(b["snapshot"]) if fresh else {}
|
||||
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}
|
||||
"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))
|
||||
@@ -83,6 +90,10 @@ class RoverControl:
|
||||
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:
|
||||
@@ -104,6 +115,8 @@ class RoverControl:
|
||||
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}
|
||||
@@ -131,9 +144,9 @@ class RoverControl:
|
||||
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)}
|
||||
"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)
|
||||
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):
|
||||
@@ -187,10 +200,10 @@ class RoverControl:
|
||||
if not s or s["id"] != session or not s["neutral_hold"]:
|
||||
return False
|
||||
snapshot = b["snapshot"]
|
||||
if (self.clock()-b["seen"] >= 1 or snapshot.get("supported") is not True
|
||||
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"] >= 1 else
|
||||
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)
|
||||
@@ -207,9 +220,26 @@ class RoverControl:
|
||||
("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:
|
||||
@@ -232,6 +262,11 @@ class RoverControl:
|
||||
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:
|
||||
@@ -241,6 +276,8 @@ class RoverControl:
|
||||
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"])
|
||||
@@ -256,11 +293,11 @@ class RoverControl:
|
||||
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"].enabled or b["diagnostics"].closing, "command": command,
|
||||
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": bool(b["diagnostics"].enabled or b["diagnostics"].closing or b["diagnostics"].export.busy),
|
||||
"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):
|
||||
@@ -269,6 +306,13 @@ class RoverControl:
|
||||
# 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.
|
||||
|
||||
@@ -334,12 +378,12 @@ class RoverControl:
|
||||
with self.lock:
|
||||
b = self._board(node)
|
||||
self._expire(b)
|
||||
if self.clock() - b["seen"] >= 1:
|
||||
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"].enabled or b["diagnostics"].closing,
|
||||
return {"watch": self.clock() < b["watch"] or s is not None or b["diagnostics"].watch_required(),
|
||||
"command": command, "control_clock": self._clock()}
|
||||
|
||||
Reference in New Issue
Block a user