feat(events): deliver state changes to the configurable operator event center
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
"""Transitions from confirmed arrivals and Core-owned control decisions. No network I/O."""
|
||||
|
||||
import time
|
||||
from collections import deque
|
||||
from uuid import uuid4
|
||||
|
||||
LINK_TIMEOUT = 20
|
||||
STOP_CAUSES = {
|
||||
"input_deadline_expired": "Истёк срок действия команды управления.",
|
||||
"operator_socket_closed": "Закрылось соединение оператора.",
|
||||
"driver_unavailable": "Драйвер контроллеров недоступен.",
|
||||
"driver_terminal": "Борт сообщил о завершении управления контроллерами.",
|
||||
"driver_restarted": "Драйвер контроллеров перезапустился.",
|
||||
"relay_changed": "Сменился сеанс бортового канала.",
|
||||
}
|
||||
|
||||
|
||||
class BoardPresence:
|
||||
"""Only a binding seen since Core startup can go missing. All calls under registry lock."""
|
||||
|
||||
def __init__(self, history, clock=time.monotonic, wall=time.time):
|
||||
self.history, self.clock, self.wall = history, clock, wall
|
||||
self.links = {}
|
||||
|
||||
def received(self, row):
|
||||
key = row["binding"]["binding_id"]
|
||||
now = self.clock()
|
||||
previous = self.links.get(key)
|
||||
if previous and now >= previous["until"]:
|
||||
self.expire(row)
|
||||
self.history.publish(
|
||||
"board.restored",
|
||||
previous["episode"] + ":up",
|
||||
"success",
|
||||
"Связь с бортом · " + row["name"],
|
||||
"Связь восстановлена.",
|
||||
at=self.wall(),
|
||||
)
|
||||
if not previous or now >= previous["until"]:
|
||||
previous = self.links[key] = {"episode": uuid4().hex, "lost": False}
|
||||
previous.update(until=now + LINK_TIMEOUT, at=self.wall() + LINK_TIMEOUT)
|
||||
|
||||
def expire(self, row):
|
||||
link = self.links.get(row["binding"]["binding_id"])
|
||||
if link and not link["lost"] and self.clock() >= link["until"]:
|
||||
self.history.publish(
|
||||
"board.lost",
|
||||
link["episode"] + ":down",
|
||||
"warning",
|
||||
"Связь с бортом · " + row["name"],
|
||||
"Борт перестал выходить на связь.",
|
||||
at=link["at"],
|
||||
)
|
||||
link["lost"] = True
|
||||
|
||||
|
||||
class ControlTransitions:
|
||||
"""Access under the control lock. Publishing/SQLite runs on the registry worker."""
|
||||
|
||||
def __init__(self):
|
||||
self.pending = deque(maxlen=128)
|
||||
self.stopped = False
|
||||
|
||||
def stop(self, reason, session, age_ms):
|
||||
if reason == "operator_stop":
|
||||
return
|
||||
if reason == "telemetry_stale":
|
||||
message = (
|
||||
f"Возраст телеметрии {round(age_ms)} мс. "
|
||||
f"Порог остановки {session['telemetry_stop_ms']} мс."
|
||||
)
|
||||
else:
|
||||
message = STOP_CAUSES.get(reason, "Управление отозвано защитой.")
|
||||
self.pending.append(("control.stop", session["id"], time.time(), message))
|
||||
self.stopped = True
|
||||
|
||||
def ready(self, session):
|
||||
if self.stopped:
|
||||
self.pending.append(
|
||||
(
|
||||
"control.ready",
|
||||
session,
|
||||
time.time(),
|
||||
"Борт подтвердил готовность управления в новом сеансе.",
|
||||
)
|
||||
)
|
||||
self.stopped = False
|
||||
|
||||
|
||||
def publish_control(history, row, stream):
|
||||
node = row["node_id"]
|
||||
with stream.lock:
|
||||
board = stream.boards.get(node)
|
||||
transitions = board.get("operator_transitions") if board else None
|
||||
batch = list(transitions.pending) if transitions else []
|
||||
for item in batch:
|
||||
kind, session, at, message = item
|
||||
history.publish(
|
||||
kind,
|
||||
f"{row['binding']['binding_id']}:{kind}:{session}",
|
||||
"warning" if kind == "control.stop" else "success",
|
||||
"Управление · " + row["name"],
|
||||
message,
|
||||
at=at,
|
||||
)
|
||||
with stream.lock:
|
||||
if transitions.pending and transitions.pending[0] == item:
|
||||
transitions.pending.popleft()
|
||||
@@ -0,0 +1,96 @@
|
||||
"""Accept bounded transition receipts from the paired Node's authenticated heartbeat."""
|
||||
|
||||
import re
|
||||
|
||||
MESSAGES = {
|
||||
"delivery.loss": (
|
||||
"warning",
|
||||
"Телеметрия",
|
||||
"Борт перестал получать подтверждения доставки телеметрии от Core.",
|
||||
),
|
||||
"delivery.recovery": (
|
||||
"success",
|
||||
"Телеметрия",
|
||||
"Core снова подтверждает борту доставку телеметрии.",
|
||||
),
|
||||
"telemetry.loss": ("warning", "Телеметрия", "Борт зафиксировал потерю телеметрии VESC."),
|
||||
"telemetry.recovery": (
|
||||
"success",
|
||||
"Телеметрия",
|
||||
"Борт подтвердил восстановление телеметрии VESC.",
|
||||
),
|
||||
"board.shutdown": ("info", "Питание", "Ubuntu начала штатное завершение работы."),
|
||||
"board.boot": ("info", "Питание", "Борт сообщил о новой загрузке Linux."),
|
||||
"camera.loss": ("warning", "Камера", "Камера отключилась от USB."),
|
||||
"camera.recovery": ("success", "Камера", "Камера обнаружена по USB."),
|
||||
"frames.loss": ("warning", "Видео", "При включённом просмотре перестали поступать кадры."),
|
||||
"frames.recovery": ("success", "Видео", "Кадры камеры снова поступают."),
|
||||
"thermal.loss": ("warning", "Температура", "Ядро включило тепловое ограничение процессора."),
|
||||
"thermal.recovery": ("success", "Температура", "Ядро сняло тепловое ограничение процессора."),
|
||||
"control.stop": (
|
||||
"warning",
|
||||
"Управление",
|
||||
"Бортовой драйвер зарегистрировал аварийное завершение сеанса управления.",
|
||||
),
|
||||
"control.ready": (
|
||||
"success",
|
||||
"Управление",
|
||||
"Борт подтвердил готовность управления в новом сеансе.",
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def valid(item):
|
||||
if (
|
||||
not isinstance(item, dict)
|
||||
or not isinstance(kind := item.get("kind"), str)
|
||||
or kind not in MESSAGES
|
||||
):
|
||||
return False
|
||||
fields = {"id", "kind", "at"}
|
||||
source = kind.partition(".")[0]
|
||||
if source in ("camera", "frames"):
|
||||
fields.add("device")
|
||||
if not isinstance(device := item.get("device"), str) or not re.fullmatch(
|
||||
r"(instax4|rsd455)_[0-9a-f]{32}", device
|
||||
):
|
||||
return False
|
||||
if source == "control":
|
||||
fields.add("session")
|
||||
if not isinstance(session := item.get("session"), str) or not re.fullmatch(
|
||||
r"[0-9a-f]{32}", session
|
||||
):
|
||||
return False
|
||||
return (
|
||||
fields == item.keys()
|
||||
and isinstance(item["id"], str)
|
||||
and bool(re.fullmatch(r"[A-Za-z0-9_-]{43}", item["id"]))
|
||||
and type(item["at"]) is int
|
||||
and 0 < item["at"] < 253402300800
|
||||
)
|
||||
|
||||
|
||||
def accept_operator_events(history, row, batch):
|
||||
if not isinstance(batch, list) or not 1 <= len(batch) <= 8 or not all(map(valid, batch)):
|
||||
return {}
|
||||
binding = row["binding"]["binding_id"]
|
||||
for item in batch:
|
||||
kind = item["kind"]
|
||||
tone, title, message = MESSAGES[kind]
|
||||
identity = f"node:{binding}:{item['id']}"
|
||||
if session := item.get("session"):
|
||||
# The driver and Core can independently observe the same stop.
|
||||
identity = f"{binding}:{kind}:{session}"
|
||||
if device := item.get("device"):
|
||||
sensor = next(
|
||||
(
|
||||
d
|
||||
for d in (row.get("sensor_state") or {}).get("items", [])
|
||||
if d.get("id") == device
|
||||
),
|
||||
{},
|
||||
)
|
||||
model = "Insta360 X4" if device.startswith("instax4_") else "RealSense D455"
|
||||
message += f" {sensor.get('name') or model} · {device[-6:]}"
|
||||
history.publish(kind, identity, tone, f"{title} · {row['name']}", message, at=item["at"])
|
||||
return {"operator_events_ack": batch[-1]["id"]}
|
||||
@@ -1,6 +1,8 @@
|
||||
"""Ephemeral, owner-bound power-off handshake. Never replay a persisted command."""
|
||||
|
||||
import sqlite3
|
||||
import time
|
||||
from contextlib import suppress
|
||||
|
||||
SCHEMA = "missioncore.node-power/v1"
|
||||
|
||||
@@ -8,6 +10,7 @@ SCHEMA = "missioncore.node-power/v1"
|
||||
class BoardPower:
|
||||
# All access is under FleetRegistry.lock; no disk queue or background retry.
|
||||
def __init__(self):
|
||||
self.notifications = None
|
||||
self.nodes = {}
|
||||
self.operations = {}
|
||||
|
||||
@@ -44,6 +47,13 @@ class BoardPower:
|
||||
"failed": "Борт не смог выполнить выключение. Проверьте состояние системы.",
|
||||
"expired": "Срок действия команды истёк. Выключение не выполнено.",
|
||||
}[state]
|
||||
if (op["state"] in ("accepted", "executing", "submitted") and self.notifications
|
||||
and not op.get("notified")):
|
||||
with suppress(OSError, sqlite3.Error):
|
||||
self.notifications.publish("board.shutdown", f"power:{binding}:{op['id']}",
|
||||
"info", "Питание · " + row["name"],
|
||||
"Борт принял команду штатного выключения.")
|
||||
op["notified"] = True
|
||||
self._expire(op, now)
|
||||
if op["state"] == "queued":
|
||||
return {
|
||||
|
||||
@@ -25,6 +25,11 @@ from .recovery import listener_addresses
|
||||
from .sensor_transient import cache as sensor_transient
|
||||
from .trust import SCHEMA, CoreTrust, PairingError, node_request, parse_invitation, pem, public_id
|
||||
|
||||
from .board_event_transitions import BoardPresence, LINK_TIMEOUT, publish_control
|
||||
from .node_operator_events import accept_operator_events
|
||||
from .uplink_notifications import publish_uplink_applied
|
||||
|
||||
|
||||
class FleetRegistry:
|
||||
"""One writer lock and durable transactions; transport never owns vehicles."""
|
||||
|
||||
@@ -57,6 +62,10 @@ class FleetRegistry:
|
||||
self.rover_telemetry_preferences = RoverTelemetryPreferences(root)
|
||||
from .uplinks import Uplinks
|
||||
self.uplinks = Uplinks(guard=self.rover_control.network_change)
|
||||
from k1link.notifications import NotificationHistory
|
||||
self.notifications = NotificationHistory(root.parent / 'notifications')
|
||||
self.board_presence = BoardPresence(self.notifications)
|
||||
self.power.notifications = self.notifications
|
||||
from .rover_channel import RoverChannel
|
||||
self.rover_channel = RoverChannel(self.rover_control)
|
||||
from .rover_configuration import RoverConfigurations
|
||||
@@ -118,7 +127,10 @@ class FleetRegistry:
|
||||
# Publish only after commit. Inventory fsync never holds the control
|
||||
# channel lock; a failed transaction cannot change its authority.
|
||||
self.rover_channel.publish(row)
|
||||
if previous and previous["binding"]["binding_id"] != row["binding"]["binding_id"]:
|
||||
self.board_presence.links.pop(previous["binding"]["binding_id"], None)
|
||||
if row["enrollment"] == "revoked":
|
||||
self.board_presence.links.pop(row["binding"]["binding_id"], None)
|
||||
self.network_profiles.revoke_node(row["node_id"])
|
||||
self.events.notify()
|
||||
|
||||
@@ -301,7 +313,7 @@ class FleetRegistry:
|
||||
row["enrollment"] == "paired"
|
||||
and last_seen is not None
|
||||
and last_seen >= self.started_at
|
||||
and time.time() - last_seen < 20
|
||||
and time.time() - last_seen < LINK_TIMEOUT
|
||||
)
|
||||
return {
|
||||
"id": row["id"],
|
||||
@@ -438,6 +450,11 @@ class FleetRegistry:
|
||||
self.routers.prune()
|
||||
self.uplinks.prune()
|
||||
active = [row for row in self.rows() if row["enrollment"] in ("pending", "paired")]
|
||||
for row in active:
|
||||
if row["enrollment"] == "paired":
|
||||
with suppress(OSError, sqlite3.Error):
|
||||
self.board_presence.expire(row)
|
||||
publish_control(self.notifications, row, self.rover_control)
|
||||
for address in {address for row in active for address in listener_addresses(row)}:
|
||||
try:
|
||||
self.listen(address)
|
||||
@@ -524,6 +541,11 @@ class FleetRegistry:
|
||||
configuration_response = self.rover_configurations.heartbeat(node_id, value)
|
||||
network_response = self.network_profiles.heartbeat(row, value)
|
||||
uplink_response = self.uplinks.heartbeat(row, value)
|
||||
try:
|
||||
self.notifications.uplink(row, self.uplinks.events(row))
|
||||
publish_uplink_applied(self.notifications, row, self.uplinks)
|
||||
except (OSError, sqlite3.Error):
|
||||
logging.getLogger(__name__).warning('Notification history unavailable')
|
||||
archive_ack = None
|
||||
archive_started = time.monotonic()
|
||||
try:
|
||||
@@ -539,6 +561,12 @@ class FleetRegistry:
|
||||
archive_elapsed = time.monotonic() - archive_started
|
||||
enrollment_response = self.device_enrollment.heartbeat(row, value)
|
||||
router_response = self.routers.heartbeat(row, value)
|
||||
try:
|
||||
from .router_notifications import publish_router_results, publish_router_incidents
|
||||
publish_router_results(self.notifications, row, self.routers.pending)
|
||||
publish_router_incidents(self.notifications, row, self.routers.latest.get(node_id))
|
||||
except (OSError, sqlite3.Error):
|
||||
logging.getLogger(__name__).warning('Router notification history unavailable')
|
||||
host = value.get("host")
|
||||
if (
|
||||
not isinstance(host, dict)
|
||||
@@ -569,13 +597,22 @@ class FleetRegistry:
|
||||
if archive_elapsed > .025 or save_elapsed > .025:
|
||||
logging.getLogger(__name__).warning(
|
||||
"fleet heartbeat timing archive_ms=%.1f save_ms=%.1f", archive_elapsed*1000, save_elapsed*1000)
|
||||
with suppress(OSError, sqlite3.Error):
|
||||
self.board_presence.received(row)
|
||||
monitor_ack = None
|
||||
try:
|
||||
monitor_ack = self.monitor.submit(node_id, value.get("monitor"))
|
||||
except (ValueError, TypeError, KeyError, sqlite3.Error):
|
||||
# Telemetry persistence failure must not block device control.
|
||||
pass
|
||||
event_ack = {}
|
||||
if value.get('operator_events_v1'):
|
||||
try:
|
||||
event_ack = accept_operator_events(self.notifications, row, value['operator_events_v1'])
|
||||
except (OSError, sqlite3.Error):
|
||||
logging.getLogger(__name__).warning('Operator events awaiting storage')
|
||||
return 200, {
|
||||
**event_ack,
|
||||
"vesc_configurations_ack": archive_ack,
|
||||
"monitor_ack": monitor_ack,
|
||||
"ok": True,
|
||||
@@ -611,4 +648,6 @@ class FleetRegistry:
|
||||
"at": now, "binding_id": row["binding"]["binding_id"],
|
||||
"agent_instance_id": binding.agent_instance_id,
|
||||
}
|
||||
with suppress(OSError, sqlite3.Error):
|
||||
self.board_presence.received(row)
|
||||
return 200, {"ok": True, "heartbeat_encoding": "gzip"}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Publish outcomes of operator commands independently of the settings window."""
|
||||
|
||||
import hashlib
|
||||
|
||||
|
||||
def publish_router_results(history, row, pending):
|
||||
for (vehicle, operation), entry in pending.items():
|
||||
if vehicle != row["id"] or entry["binding"] != row["binding"]["binding_id"]:
|
||||
continue
|
||||
receipt = entry["public"]
|
||||
state = receipt["state"]
|
||||
if receipt.get("action") != "policy" or state not in {"complete", "error", "unknown"}:
|
||||
continue
|
||||
# A late definitive result may follow an unconfirmed timeout.
|
||||
if entry.get("notified_state") == state:
|
||||
continue
|
||||
if state == "complete":
|
||||
tone = "success"
|
||||
message = (
|
||||
"Роутер подтвердил сохранение и применение настроек. "
|
||||
"Фактический канал показан в обзоре роутера."
|
||||
)
|
||||
elif state == "unknown":
|
||||
tone = "warning"
|
||||
message = (
|
||||
"Результат применения не подтверждён. "
|
||||
"Проверьте текущее состояние роутера перед повторной командой."
|
||||
)
|
||||
else:
|
||||
tone = "error"
|
||||
message = {
|
||||
"router_busy": (
|
||||
"Настройки не применены: роутер занят другой операцией. "
|
||||
"Дождитесь её завершения и повторите применение."
|
||||
),
|
||||
"router_conflict": (
|
||||
"Настройки не применены: состояние роутера изменилось. "
|
||||
"Обновите форму перед новой командой."
|
||||
),
|
||||
"router_unavailable": "Настройки не применены: роутер недоступен.",
|
||||
"access_rejected": "Роутер отклонил доступ. Проверьте настройки доступа.",
|
||||
"expired": "Команда не выполнена: срок запроса истёк.",
|
||||
}.get(
|
||||
receipt.get("error"),
|
||||
"Роутер не подтвердил применение настроек. "
|
||||
"Подробности доступны в разделе «Управление».",
|
||||
)
|
||||
identity = (
|
||||
"router:"
|
||||
+ hashlib.sha256(
|
||||
f"{row['node_id']}:{entry['binding']}:{operation}:{state}".encode()
|
||||
).hexdigest()
|
||||
)
|
||||
kind = "router.applied" if state == "complete" else "router.error"
|
||||
history.publish(kind, identity, tone, "Режим роутера · " + row["name"], message)
|
||||
entry["notified_state"] = state
|
||||
|
||||
|
||||
def publish_router_incidents(history, row, cached):
|
||||
if not cached or cached.get("invalid") or cached["binding"] != row["binding"]["binding_id"]:
|
||||
return
|
||||
snapshot = cached["state"]
|
||||
last = snapshot["journal"]["last_sequence"]
|
||||
scope = row["node_id"] + ":" + cached["binding"]
|
||||
previous = history.journal_position(scope)
|
||||
if previous == last:
|
||||
return
|
||||
if previous is not None and previous < last:
|
||||
names = {
|
||||
"aggregation": "Агрегация",
|
||||
"direct": "Одна SIM-карта",
|
||||
"ready": "Доступен",
|
||||
"unreachable": "Недоступен",
|
||||
"access_required": "Требуется доступ",
|
||||
"access_rejected": "Доступ отклонён",
|
||||
"incompatible": "Несовместим",
|
||||
}
|
||||
for event in snapshot["events"]:
|
||||
key = {
|
||||
"mode_changed": "router.mode",
|
||||
"operator_changed": "router.operator",
|
||||
"availability": "router.availability",
|
||||
}.get(event["code"])
|
||||
if not key or event["sequence"] <= previous:
|
||||
continue
|
||||
label = {
|
||||
"router.mode": "Режим роутера",
|
||||
"router.operator": f"Оператор SIM{event['slot']}",
|
||||
"router.availability": "Связь с роутером",
|
||||
}[key]
|
||||
before, after = (
|
||||
names.get(event[k], event[k]) or "Нет данных" for k in ("before", "after")
|
||||
)
|
||||
identity = f"router:{scope}:{event['boot_id']}:{event['sequence']}"
|
||||
tone = (
|
||||
("warning" if event["after"] != "ready" else "success")
|
||||
if key == "router.availability"
|
||||
else "info"
|
||||
)
|
||||
history.publish(
|
||||
key,
|
||||
identity,
|
||||
tone,
|
||||
label + " · " + row["name"],
|
||||
f"{before} → {after}",
|
||||
at=event["at"],
|
||||
)
|
||||
history.advance_journal(scope, last)
|
||||
@@ -8,6 +8,7 @@ import secrets
|
||||
import threading
|
||||
import time
|
||||
|
||||
from .board_event_transitions import ControlTransitions
|
||||
from .rover_diagnostics import RoverDiagnostics
|
||||
from .rover_observation_evidence import ObservationEvidence
|
||||
from .rover_telemetry_policy import DEFAULT_MS, telemetry_stop_ms
|
||||
@@ -25,7 +26,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, self.diagnostic_root / hashlib.sha256(node.encode()).hexdigest()[:24] if self.diagnostic_root is not None else None),"observation":ObservationEvidence(self.clock)}
|
||||
self.boards[node]={"operator_transitions":ControlTransitions(),"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):
|
||||
@@ -78,6 +79,7 @@ class RoverControl:
|
||||
if session is None:
|
||||
return
|
||||
b["session"] = None
|
||||
b["operator_transitions"].stop(reason, session, max(0., self.clock() - b["seen"]) * 1000)
|
||||
observed = b["snapshot"] if snapshot is None else snapshot
|
||||
b["diagnostics"].control_stop.record(
|
||||
reason, session, core_instance=self.clock_id,
|
||||
@@ -291,6 +293,8 @@ class RoverControl:
|
||||
s = None
|
||||
command = None
|
||||
if s:
|
||||
if publish and snapshot.get("session_id") == s["id"] and snapshot.get("state") in ("ready", "driving"):
|
||||
b["operator_transitions"].ready(s["id"])
|
||||
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,
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Only a confirmed operator switch to the verified target is an applied event."""
|
||||
|
||||
|
||||
def publish_uplink_applied(history, row, uplinks):
|
||||
node = row["node_id"]
|
||||
operation = uplinks.operations.get(node)
|
||||
if (
|
||||
not operation
|
||||
or operation["phase"] != "applied"
|
||||
or operation.get("notified")
|
||||
or operation.get("reported_only")
|
||||
or operation["binding"] != row["binding"]["binding_id"]
|
||||
):
|
||||
return
|
||||
view = uplinks.view(row)
|
||||
if not view["path_verified"] or view["current_id"] != operation["target"]:
|
||||
return
|
||||
candidate = next((c for c in view["candidates"] if c["id"] == view["current_id"]), None)
|
||||
if candidate:
|
||||
channel = "Wi-Fi" if candidate["kind"] == "wifi" else "Ethernet"
|
||||
history.publish(
|
||||
"uplink.applied",
|
||||
f"uplink:{node}:{operation['id']}",
|
||||
"success",
|
||||
"Связь с бортом · " + row["name"],
|
||||
f"Борт подтвердил связь с Core через {channel}.",
|
||||
)
|
||||
operation["notified"] = True
|
||||
Reference in New Issue
Block a user