Package the adapter SDK boundary and runtime lifecycle. Confirm admitted CAN transactions, bound retained data and test failure paths with synthetic hardware.
390 lines
17 KiB
Python
390 lines
17 KiB
Python
"""USB identity/hotplug and session-bound operations. Raw frames never reach disk."""
|
||
|
||
import copy
|
||
import hashlib
|
||
import json
|
||
import re
|
||
import threading
|
||
import time
|
||
import uuid
|
||
from collections import OrderedDict
|
||
from datetime import UTC, datetime
|
||
from pathlib import Path
|
||
|
||
from . import MODEL, SCHEMA, VERSION
|
||
from .contracts import ACTIONS, channel, configuration, integer, transmission
|
||
from .discovery import device_id, discover
|
||
from .worker import Link
|
||
|
||
|
||
def utc():
|
||
return datetime.now(UTC).isoformat()
|
||
|
||
|
||
class Device:
|
||
def __init__(self, attachment):
|
||
self.attachment = attachment
|
||
self.session = "usbcan_" + uuid.uuid4().hex
|
||
self.opened = utc()
|
||
self.link = None
|
||
self.status = None
|
||
self.error = None
|
||
self.retry_at = 0
|
||
self.failures = 0
|
||
self.revision = 0
|
||
self.preview = None
|
||
self.lock = threading.RLock()
|
||
self.activity = None
|
||
|
||
@property
|
||
def id(self):
|
||
return (
|
||
device_id("serial:" + self.status["identity"]["serial"])
|
||
if self.status
|
||
else self.attachment.id
|
||
)
|
||
|
||
def call(self, action, params):
|
||
# Caller holds the device lock. Keep only bounded operation metadata,
|
||
# never frames, so a rejected poll identifies its competing owner.
|
||
self.activity = (action, time.monotonic())
|
||
try:
|
||
return self.link.call(action, params)
|
||
finally:
|
||
self.activity = None
|
||
|
||
def close(self):
|
||
if self.link:
|
||
self.link.close()
|
||
self.link, self.preview = None, None
|
||
self.session, self.opened = "usbcan_" + uuid.uuid4().hex, utc()
|
||
|
||
|
||
class Service:
|
||
def __init__(self, root="/var/lib/mission-core-usb-can", discover_fn=discover, factory=Link):
|
||
self.root = Path(root)
|
||
self.discover_fn, self.factory = discover_fn, factory
|
||
self.devices = {}
|
||
self.lock = threading.RLock()
|
||
self.receipts = OrderedDict()
|
||
self.instance = "usbcan_" + uuid.uuid4().hex
|
||
self.revision = 0
|
||
|
||
def scan(self):
|
||
attachments = {item.binding: item for item in self.discover_fn()}
|
||
with self.lock:
|
||
removed = [
|
||
self.devices.pop(k)
|
||
for k, d in list(self.devices.items())
|
||
if attachments.get(k) != d.attachment
|
||
]
|
||
for key, item in attachments.items():
|
||
if key not in self.devices:
|
||
self.devices[key] = Device(item)
|
||
devices = list(self.devices.values())
|
||
for d in removed:
|
||
with d.lock:
|
||
d.close()
|
||
# SDK indices are enumeration-local, so verify opened FD on every attempt.
|
||
for index, d in enumerate(devices):
|
||
if not d.lock.acquire(blocking=False):
|
||
continue
|
||
try:
|
||
if d.link and not d.link.alive:
|
||
d.close()
|
||
d.session, d.opened = "usbcan_" + uuid.uuid4().hex, utc()
|
||
d.status = None
|
||
if d.link is None and time.monotonic() >= d.retry_at:
|
||
d.failures += 1
|
||
d.retry_at = time.monotonic() + min(60, 2 ** min(d.failures, 6))
|
||
d.link = self.factory(
|
||
(index + d.failures - 1) % max(1, len(devices)), d.attachment.path
|
||
)
|
||
d.status = d.link.initial
|
||
# Saved configuration does not enable CAN or repeat a job.
|
||
saved = self.root / (d.id + ".json")
|
||
if saved.exists():
|
||
document = json.loads(saved.read_text())
|
||
if (
|
||
not isinstance(document["channels"], list)
|
||
or len(document["channels"]) != 2
|
||
):
|
||
raise ValueError("Сохранённая конфигурация не содержит два канала.")
|
||
for ch, config in enumerate(document["channels"]):
|
||
d.status = d.call(
|
||
"configure",
|
||
{"channel": channel(ch), "config": configuration(config)},
|
||
)
|
||
d.revision = integer(document["revision"], 0, 2**31 - 1)
|
||
d.error, d.failures = None, 0
|
||
elif d.link is not None:
|
||
d.status = d.call("status", {})
|
||
|
||
except (OSError, ValueError, KeyError, EOFError) as error:
|
||
d.error = str(error)[:250]
|
||
d.close()
|
||
finally:
|
||
d.lock.release()
|
||
with self.lock:
|
||
self.revision += 1
|
||
|
||
def bridge_inventory(self):
|
||
with self.lock:
|
||
devices = list(self.devices.values())
|
||
ids = [d.id for d in devices]
|
||
return {
|
||
"items": [
|
||
{
|
||
"id": d.id,
|
||
"session_id": d.session,
|
||
"attachment_id": d.attachment.id,
|
||
"name": "USB-CAN-FD-B · " + d.status["identity"]["serial"],
|
||
"online": True,
|
||
"channels": 2,
|
||
}
|
||
for d in devices
|
||
if d.status and d.link and d.link.alive and ids.count(d.id) == 1
|
||
]
|
||
}
|
||
|
||
def bridge(self, request):
|
||
if (
|
||
not isinstance(request, dict)
|
||
or set(request) != {"adapter", "session", "action", "parameters"}
|
||
or request["action"] not in ("open", "close", "send", "poll")
|
||
or not isinstance(request["parameters"], dict)
|
||
):
|
||
raise ValueError("Invalid VESC bridge request")
|
||
with self.lock:
|
||
matches = [d for d in self.devices.values() if d.id == request["adapter"]]
|
||
if len(matches) != 1:
|
||
raise ValueError("Адаптер CAN недоступен или его идентификатор повторяется.")
|
||
d = matches[0]
|
||
if not d.lock.acquire(timeout=0.2):
|
||
action, started = d.activity or ("lifecycle", time.monotonic())
|
||
raise OSError(f"Адаптер CAN занят: {action}, {time.monotonic() - started:.3f} с.")
|
||
try:
|
||
if d.session != request["session"] or not d.link or not d.link.alive:
|
||
raise ValueError("Подключение адаптера CAN изменилось.")
|
||
return d.call("bridge." + request["action"], request["parameters"])
|
||
except (OSError, EOFError):
|
||
d.close()
|
||
raise
|
||
finally:
|
||
d.lock.release()
|
||
|
||
def prepare_safe(self):
|
||
with self.lock:
|
||
devices = list(self.devices.values())
|
||
for device in devices:
|
||
if not device.lock.acquire(timeout=1):
|
||
return False
|
||
try:
|
||
if device.link:
|
||
status = device.call("status", {})
|
||
if any(channel["running"] for channel in status["channels"]):
|
||
return False
|
||
except (OSError, EOFError):
|
||
return False
|
||
finally:
|
||
device.lock.release()
|
||
return True
|
||
|
||
def inventory(self, node):
|
||
with self.lock:
|
||
devices = list(self.devices.values())
|
||
ids = [d.id for d in devices]
|
||
items = []
|
||
for d in devices:
|
||
unique = ids.count(d.id) == 1 and d.status is not None
|
||
available = unique and d.link is not None and d.link.alive
|
||
identity = d.status["identity"] if unique else None
|
||
status = copy.deepcopy(d.status) if available else None
|
||
if status:
|
||
status.pop("frames", None)
|
||
identifier = d.id if unique else d.attachment.id
|
||
message = (
|
||
d.error
|
||
if ids.count(d.id) == 1
|
||
else "Повторяющийся серийный номер. Управление недоступно."
|
||
)
|
||
items.append(
|
||
{
|
||
"id": identifier,
|
||
"attachment_id": d.attachment.id,
|
||
"kind": MODEL,
|
||
"name": "USB-CAN-FD-B" + (" · " + identity["serial"] if identity else ""),
|
||
"model": "Waveshare USB-CAN-FD-B",
|
||
"firmware": identity["firmware"] if identity else None,
|
||
"initializable": True,
|
||
"prepared": True,
|
||
"configured": unique,
|
||
"verified": bool(available),
|
||
"online": True,
|
||
"usb": d.attachment.speed,
|
||
"connection_label": "USB " + d.attachment.usb,
|
||
"preparation_safe": not (
|
||
status and any(c["running"] for c in status["channels"])
|
||
),
|
||
"layers": [],
|
||
"can_status": {**(status or {}), "revision": d.revision, "message": message},
|
||
"snapshot": {
|
||
"context": {
|
||
"session_id": d.session,
|
||
"device": {
|
||
"device_id": identifier,
|
||
"model": {
|
||
"plugin_id": "missioncore.usb-can",
|
||
"plugin_version": VERSION,
|
||
"model_id": MODEL,
|
||
},
|
||
"stability": "stable" if unique else "provisional",
|
||
"basis": "hardware-identifier" if unique else "transport-local",
|
||
},
|
||
"execution": {
|
||
"node_id": node,
|
||
"agent_instance_id": self.instance,
|
||
"platform": "linux",
|
||
},
|
||
"opened_at": d.opened,
|
||
},
|
||
"revision": self.revision,
|
||
"observed_at": utc(),
|
||
"enrollment": "enrolled" if unique else "empty",
|
||
"acquisition": "idle",
|
||
"connectivity": "connected" if available else "degraded",
|
||
"message": message,
|
||
},
|
||
}
|
||
)
|
||
return {"items": items}
|
||
|
||
def execute(self, command):
|
||
if command.get("api_version") != SCHEMA or command.get("kind") != "OperationRequest":
|
||
raise ValueError("Неверный контракт.")
|
||
op = command.get("operation_id", "")
|
||
if not re.fullmatch(r"op_[0-9a-f]{32}", op) or command.get("idempotency_key") != op:
|
||
raise ValueError("Неверный идентификатор операции.")
|
||
action, params = command.get("action_id"), command.get("parameters")
|
||
if action not in ACTIONS or not isinstance(params, dict):
|
||
raise ValueError("Неподдерживаемая операция.")
|
||
start = datetime.fromisoformat(command["requested_at"].replace("Z", "+00:00"))
|
||
end = datetime.fromisoformat(command["deadline_at"].replace("Z", "+00:00"))
|
||
if (
|
||
start.tzinfo is None
|
||
or end.tzinfo is None
|
||
or not 0 < (end - start).total_seconds() <= (360 if action == "verify" else 60)
|
||
or datetime.now(UTC) >= end
|
||
):
|
||
raise ValueError("Срок запроса истёк.")
|
||
digest = hashlib.sha256(json.dumps(command, sort_keys=True).encode()).hexdigest()
|
||
with self.lock:
|
||
# Keep receipts beyond every admitted deadline. Never evict an
|
||
# unexpired identity to make room for a retry.
|
||
now = time.monotonic()
|
||
for key, entry in list(self.receipts.items()):
|
||
if now - entry[0] > 380:
|
||
del self.receipts[key]
|
||
if op in self.receipts:
|
||
entry = self.receipts[op]
|
||
if entry[1] != digest:
|
||
raise ValueError("Идентификатор уже использован.")
|
||
return entry[2]
|
||
if len(self.receipts) >= 256:
|
||
raise ValueError("Слишком много операций.")
|
||
selected = [d for d in self.devices.values() if d.id == command["session"]["device_id"]]
|
||
if (
|
||
len(selected) != 1
|
||
or not selected[0].link
|
||
or selected[0].session != command["session"]["session_id"]
|
||
):
|
||
raise ValueError("Сеанс USB изменился. Обновите устройство.")
|
||
d = selected[0]
|
||
result = {
|
||
"state": "unknown",
|
||
"error": "Операция уже принята; повторная отправка запрещена.",
|
||
}
|
||
self.receipts[op] = (now, digest, result)
|
||
try:
|
||
with d.lock:
|
||
if d.session != command["session"]["session_id"] or not d.link:
|
||
raise ValueError("Сеанс USB изменился.")
|
||
result = {"state": "complete", "result": self.perform(d, action, params)}
|
||
except (OSError, ValueError, KeyError, TypeError, EOFError) as error:
|
||
result = {"state": "error", "error": str(error)[:300]}
|
||
with self.lock:
|
||
self.receipts[op] = (now, digest, result)
|
||
return result
|
||
|
||
def perform(self, d, action, params):
|
||
if action in ("details", "verify", "can.status"):
|
||
if set(params) - {"after"}:
|
||
raise ValueError("Неизвестные параметры просмотра.")
|
||
after = integer(params.get("after", d.status["sequence"]), 0, 2**53 - 1)
|
||
status = d.call("status", {"after": after})
|
||
else:
|
||
ch = channel(params.get("channel"))
|
||
if action == "can.configure":
|
||
if (
|
||
set(params) != {"channel", "revision", "config"}
|
||
or params["revision"] != d.revision
|
||
):
|
||
raise ValueError("Конфигурация изменилась. Прочитайте её заново.")
|
||
config = configuration(params["config"])
|
||
status = d.call("configure", {"channel": ch, "config": config})
|
||
d.revision += 1
|
||
d.preview = None
|
||
self.root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||
saved = self.root / (d.id + ".json")
|
||
temporary = self.root / (d.id + ".tmp")
|
||
temporary.write_text(
|
||
json.dumps(
|
||
{
|
||
"revision": d.revision,
|
||
"channels": [v["config"] for v in status["channels"]],
|
||
}
|
||
)
|
||
)
|
||
temporary.replace(saved)
|
||
elif action == "can.transmit.preview":
|
||
if set(params) != {"channel", "plan"}:
|
||
raise ValueError("Неверные параметры передачи.")
|
||
plan = transmission(params["plan"])
|
||
token = uuid.uuid4().hex
|
||
d.preview = (token, ch, plan, time.monotonic() + 60, d.revision, d.session)
|
||
return {
|
||
"token": token,
|
||
"channel": ch,
|
||
"plan": plan,
|
||
"expires_in": 60,
|
||
"total": len(plan["frames"]) * plan["repeat"],
|
||
}
|
||
elif action == "can.transmit.apply":
|
||
if (
|
||
set(params) != {"channel", "token", "confirmed"}
|
||
or params["confirmed"] is not True
|
||
):
|
||
raise ValueError("Подтвердите проверенное задание передачи.")
|
||
preview, d.preview = d.preview, None
|
||
if (
|
||
not preview
|
||
or (preview[0], preview[1], preview[4], preview[5])
|
||
!= (params["token"], ch, d.revision, d.session)
|
||
or time.monotonic() >= preview[3]
|
||
):
|
||
raise ValueError("Подтверждение передачи истекло.")
|
||
status = d.call("transmit", {"channel": ch, "plan": preview[2]})
|
||
else:
|
||
if set(params) != {"channel"}:
|
||
raise ValueError("Неверные параметры канала.")
|
||
method = {
|
||
"can.start": "start",
|
||
"can.stop": "stop",
|
||
"can.clear": "clear",
|
||
"can.transmit.stop": "transmit.stop",
|
||
}[action]
|
||
d.preview = None
|
||
status = d.call(method, {"channel": ch})
|
||
d.status = {**status, "frames": []}
|
||
return {**status, "revision": d.revision, "session_id": d.session, "device_id": d.id}
|