Persist rover observation configuration and calibrate Insta360 panorama

This commit is contained in:
DCCONSTRUCTIONS
2026-10-09 18:17:54 +03:00
parent c43b097a3a
commit b4dab01f2a
36 changed files with 1271 additions and 50 deletions
@@ -0,0 +1,50 @@
"""Validation and read-only migration of the former operator-local preferences."""
import hashlib
import json
from pathlib import Path
SCHEMA = "missioncore.observation/v1"
class RevisionConflict(ValueError):
pass
def path(root: Path, vehicle: str) -> Path:
return root / "observation" / hashlib.sha256(vehicle.encode()).hexdigest() / "method.json"
def validate(document: dict) -> dict:
if not isinstance(document, dict) or set(document) != {"layouts", "cameras"}:
raise ValueError("Invalid observation configuration")
if len(json.dumps(document, allow_nan=False).encode()) > 500000:
raise ValueError("Observation configuration is too large")
layouts, cameras = document["layouts"], document["cameras"]
if not isinstance(layouts, dict) or layouts.get("version") != 1:
raise ValueError("Invalid layouts")
if not isinstance(cameras, dict) or len(cameras) > 128:
raise ValueError("Invalid camera settings")
for device, camera in cameras.items():
if not isinstance(device, str) or not 0 < len(device) <= 512 or not isinstance(camera, dict):
raise ValueError("Invalid camera identity")
if set(camera) != {"rotations", "panoramaYaw"} or not isinstance(camera["rotations"], dict):
raise ValueError("Invalid camera presentation")
if set(camera["rotations"]) - {"left", "right"}:
raise ValueError("Unknown lens")
if any(type(v) is not int or v not in (0, 90, 180, 270) for v in camera["rotations"].values()):
raise ValueError("Invalid rotation")
yaw = camera["panoramaYaw"]
if type(yaw) not in (int, float) or not 0 <= yaw < 360:
raise ValueError("Invalid panorama direction")
return document
def read(root: Path, vehicle: str) -> dict:
target = path(root, vehicle)
if not target.exists():
return {"schema": SCHEMA, "revision": 0, "document": None}
if target.is_symlink() or target.stat().st_size > 1100000:
raise ValueError("Invalid observation file")
value = json.loads(target.read_bytes())
if (not isinstance(value, dict) or set(value) != {"schema", "revision", "document"}
or value["schema"] != SCHEMA or type(value["revision"]) is not int
or not 1 <= value["revision"] < 2**53-1):
raise ValueError("Invalid observation file")
validate(value["document"])
return value
+4
View File
@@ -46,6 +46,8 @@ class FleetRegistry:
self.monitor = MonitorReceiver(root)
from .rover_control import RoverControl
self.rover_control = RoverControl()
from .rover_configuration import RoverConfigurations
self.rover_configurations = RoverConfigurations(root)
self.trust = CoreTrust(root)
path = root / "fleet.sqlite3"
if path.is_symlink():
@@ -489,6 +491,7 @@ class FleetRegistry:
return 400, {"error": "Invalid Node inventory"}
sensor_state = sensors.validate_inventory(value, node_id)
sensor_response = sensors.heartbeat(row, value)
configuration_response = self.rover_configurations.heartbeat(node_id, value)
archive_ack = None
archive_started = time.monotonic()
try:
@@ -544,6 +547,7 @@ class FleetRegistry:
"monitor_ack": monitor_ack,
"ok": True,
"client_pem": row["binding"]["client_pem"],
**configuration_response,
**sensor_response,
**enrollment_response,
}
+117
View File
@@ -0,0 +1,117 @@
"""Confirmed onboard configuration mirror and bounded paired-channel requests.
Only an authenticated Node heartbeat can write a confirmed configuration. A
browser request is a transient proposal; its HTTP success requires onboard ACK.
"""
from __future__ import annotations
import copy
import hashlib
import json
import math
import secrets
import threading
import time
from pathlib import Path
from .observation_configuration import validate, RevisionConflict
from .trust import atomic_private
SCHEMA = "missioncore.rover-configuration/v1"
class Unavailable(RuntimeError):
pass
class RoverConfigurations:
def __init__(self, root: Path):
self.root = root / "rover-configurations"
self.condition = threading.Condition()
self.live: dict[str, dict] = {}
self.pending: dict[str, dict] = {}
def path(self, node: str) -> Path:
return self.root / hashlib.sha256(node.encode()).hexdigest() / "Rover Config.json"
def validate(self, node: str, value: dict) -> dict:
if (not isinstance(value, dict) or set(value)-{"schema", "node_id", "name", "revision", "observation", "last_change"}
or value.get("schema") != SCHEMA or value.get("node_id") != node
or type(value.get("revision")) is not int or not 0 <= value["revision"] < 2**53-1
or not isinstance(value.get("name"), str) or len(value["name"]) > 256
or "observation" not in value
or ("last_change" in value and (not isinstance(value["last_change"], str) or len(value["last_change"]) != 32))):
raise ValueError("Invalid onboard configuration")
if value["observation"] is not None:
validate(value["observation"])
return value
def _mirror(self, node: str) -> dict | None:
path = self.path(node)
if not path.exists():
return None
if path.is_symlink() or path.stat().st_size > 524288:
raise ValueError("Invalid configuration mirror")
return self.validate(node, json.loads(path.read_bytes()))
def view(self, node: str) -> dict:
with self.condition:
live = self.live.get(node, {})
writable = live.get("ready", False) and time.monotonic()-live.get("seen", 0) <= 15
value = live.get("configuration") or self._mirror(node)
return {"schema": SCHEMA, "revision": value["revision"] if value else 0,
"document": value["observation"] if value else None,
"source": "onboard" if writable else "mirror", "writable": bool(writable),
"available": value is not None}
def heartbeat(self, node: str, payload: dict) -> dict:
with self.condition:
offered = payload.get("rover_configuration")
value = None
if isinstance(offered, dict) and offered.get("state") == "ready":
try:
value = self.validate(node, offered["configuration"])
target = self.path(node)
if self._mirror(node) != value:
target.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
atomic_private(target, (json.dumps(value, ensure_ascii=False, indent=2)+"\n").encode())
except (KeyError, ValueError, TypeError, OSError):
value = None
self.live[node] = {"ready": value is not None, "configuration": copy.deepcopy(value), "seen": time.monotonic()}
pending = self.pending.get(node)
if pending is None:
return {}
command = pending["command"]
if value is not None:
result = offered.get("result")
# last_change survives Node restart and lost response packets.
if (value.get("last_change") == command["id"]
and value["revision"] == command["expected_revision"]+1
and value["observation"] == command["observation"]):
pending["result"] = self.view(node)
elif isinstance(result, dict) and result.get("id") == command["id"]:
pending["error"] = "conflict" if result.get("state") == "conflict" else "unavailable"
if "result" in pending or "error" in pending:
self.condition.notify_all()
return {}
if value is None or time.time() >= command["expires_at"]:
return {}
return {"rover_configuration_change": copy.deepcopy(command)}
def update(self, node: str, name: str, document: dict, revision: int, *, timeout: float = 16) -> dict:
validate(document)
with self.condition:
before = self.view(node)
if not before["writable"]:
raise Unavailable("Борт не подтвердил готовность сохранять конфигурацию. Изменения пока не сохранены.")
if before["revision"] != revision or node in self.pending:
raise RevisionConflict("Конфигурация уже изменена или сохраняется в другом окне. Загрузите настройки с борта.")
request = {"command": {"id": secrets.token_hex(16), "name": name,
"expected_revision": revision, "observation": copy.deepcopy(document),
"expires_at": math.ceil(time.time()+timeout)}}
self.pending[node] = request
try:
self.condition.wait_for(lambda: "result" in request or "error" in request, timeout)
if "result" in request:
return request["result"]
if request.get("error") == "conflict":
raise RevisionConflict("Конфигурация на борту изменилась. Загрузите её перед повторным сохранением.")
raise Unavailable("Подтверждение записи на борт не получено. Загрузите настройки, чтобы проверить результат.")
finally:
self.pending.pop(node, None)
+52
View File
@@ -99,6 +99,58 @@ def board_layout_patch(vehicle_id: str, body: BoardLayoutChange, response: Respo
raise HTTPException(500, "Не удалось сохранить раскладку аппарата.") from None
class ObservationConfigurationChange(BaseModel):
model_config = ConfigDict(extra="forbid")
expected_revision: int = Field(ge=0, lt=2**53-1, strict=True)
document: dict
@router.get("/{vehicle_id}/observation-configuration")
def observation_configuration_read(vehicle_id: str, response: Response,
fleet: Annotated[FleetRegistry, Depends(local_operator)]):
response.headers["Cache-Control"] = "no-store"
try:
with fleet.lock:
row = fleet.find(vehicle_id)
value = fleet.rover_configurations.view(row["node_id"])
# A one-time draft may migrate only after reading the board's empty
# configuration. It becomes durable solely through the normal PUT/ACK.
if value["available"] and value["document"] is None:
from k1link.fleet.observation_configuration import read
value["draft"] = read(fleet.root, vehicle_id)["document"]
return value
except PairingError as error:
raise HTTPException(404, str(error)) from None
except (OSError, ValueError):
raise HTTPException(500, "Не удалось прочитать настройки центра наблюдения.") from None
@router.put("/{vehicle_id}/observation-configuration")
def observation_configuration_write(vehicle_id: str, body: ObservationConfigurationChange,
response: Response,
fleet: Annotated[FleetRegistry, Depends(local_operator)]):
from k1link.fleet.observation_configuration import RevisionConflict
from k1link.fleet.rover_configuration import Unavailable
response.headers["Cache-Control"] = "no-store"
try:
with fleet.lock:
row = fleet.find(vehicle_id)
if row["enrollment"] != "paired":
raise Unavailable("Борт не подключён.")
# Never hold the fleet lock while waiting for its authenticated heartbeat.
return fleet.rover_configurations.update(row["node_id"], row["name"], body.document, body.expected_revision)
except PairingError as error:
raise HTTPException(404, str(error)) from None
except RevisionConflict as error:
raise HTTPException(409, str(error)) from None
except Unavailable as error:
raise HTTPException(503, str(error)) from None
except ValueError:
raise HTTPException(422, "Недопустимая конфигурация наблюдения.") from None
except OSError:
raise HTTPException(500, "Не удалось сохранить настройки центра наблюдения.") from None
@router.get("/{vehicle_id}/monitor")
def board_monitor(vehicle_id: str, response: Response,
fleet: Annotated[FleetRegistry, Depends(local_operator)],