feat(fleet): preserve operator VESC integration before final driver merge
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
"""Ephemeral operator leases. No motor calls, command queue or persisted motion."""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import math
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
class RoverControl:
|
||||
def __init__(self, clock=time.monotonic):
|
||||
self.clock = clock
|
||||
self.lock = threading.RLock()
|
||||
self.changed = threading.Condition(self.lock)
|
||||
self.boards = {}
|
||||
self.clock_id = secrets.token_hex(16)
|
||||
|
||||
def _board(self, node):
|
||||
return self.boards.setdefault(node, {"seen": -1e9, "watch": 0, "snapshot": {},
|
||||
"session": None, "relay": None})
|
||||
|
||||
def view(self, node):
|
||||
with self.lock:
|
||||
b = self._board(node)
|
||||
b["watch"] = self.clock() + 2
|
||||
fresh = self.clock() - b["seen"] < 1
|
||||
self._expire(b)
|
||||
return {"fresh": fresh, "snapshot": copy.deepcopy(b["snapshot"]) if fresh else {},
|
||||
"controlling": b["session"] is not None}
|
||||
|
||||
def _expire(self, b):
|
||||
if b["session"] and self.clock() >= b["session"]["until"]:
|
||||
b["session"] = None
|
||||
|
||||
def arm(self, node, body):
|
||||
if (set(body) != {"standstill_confirmed", "current_a", "max_erpm"}
|
||||
or body["standstill_confirmed"] is not True
|
||||
or type(body["current_a"]) not in (int, float)
|
||||
or not .5 <= body["current_a"] <= 30
|
||||
or type(body["max_erpm"]) not in (int, float)
|
||||
or not 300 <= body["max_erpm"] <= 3000):
|
||||
raise ValueError("Подтвердите остановку и выберите допустимые пределы.")
|
||||
with self.lock:
|
||||
b = self._board(node)
|
||||
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 snapshot.get("state") in ("preparing", "ready", "driving", "stopping"):
|
||||
raise ValueError("Дождитесь завершения предыдущего управления.")
|
||||
identifier = secrets.token_hex(16)
|
||||
b["session"] = {"id": identifier, "sequence": 0, "until": self.clock()+.4,
|
||||
"left": 0, "right": 0, "settings": copy.deepcopy(body)}
|
||||
self.changed.notify_all()
|
||||
return {"session_id": identifier}
|
||||
|
||||
def command(self, node, body):
|
||||
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)
|
||||
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["sequence"]:
|
||||
raise ValueError("Устаревшая команда отклонена.")
|
||||
if body["stop"]:
|
||||
b["session"] = None
|
||||
else:
|
||||
s.update(sequence=body["sequence"], left=body["left"], right=body["right"],
|
||||
until=self.clock()+.4)
|
||||
self.changed.notify_all()
|
||||
return {"accepted_sequence": body["sequence"]}
|
||||
|
||||
def exchange(self, node, body):
|
||||
"""Called only after normal paired-certificate/binding authentication."""
|
||||
snapshot = body.get("rover")
|
||||
relay = body.get("relay_id")
|
||||
if not isinstance(snapshot, dict) or not isinstance(relay, str) or len(relay) != 32:
|
||||
raise ValueError("Invalid rover exchange")
|
||||
with self.lock:
|
||||
b = self._board(node)
|
||||
if b["relay"] != relay:
|
||||
b["session"] = None # No resume after relay restart/rebind.
|
||||
if b["snapshot"].get("instance") != snapshot.get("instance"):
|
||||
b["session"] = None # Driver restarts also revoke the browser lease.
|
||||
b.update(relay=relay, snapshot=copy.deepcopy(snapshot), seen=self.clock())
|
||||
self._expire(b)
|
||||
s = b["session"]
|
||||
if s and snapshot.get("session_id") == s["id"] and snapshot.get("state") in (
|
||||
"stopped", "fault", "receiver"):
|
||||
b["session"] = s = None
|
||||
command = None
|
||||
if s:
|
||||
command = {k: copy.deepcopy(v) for k,v in s.items() if k != "until"}
|
||||
command["ttl_ms"] = max(0, min(400, int((s["until"]-self.clock())*1000)))
|
||||
return {"watch": self.clock() < b["watch"] or s is not None, "command": command,
|
||||
"control_clock": self._clock()}
|
||||
|
||||
def _clock(self):
|
||||
return {"instance": self.clock_id, "monotonic_ms": self.clock()*1000}
|
||||
|
||||
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"] >= 1:
|
||||
b["session"] = None
|
||||
s = b["session"] if b["relay"] == relay else None
|
||||
command = None
|
||||
if s:
|
||||
command = {k: copy.deepcopy(v) for k,v in s.items() if k != "until"}
|
||||
command["expires_mono_ms"] = s["until"]*1000
|
||||
return {"watch": self.clock() < b["watch"] or s is not None,
|
||||
"command": command, "control_clock": self._clock()}
|
||||
Reference in New Issue
Block a user