Files
DCCONSTRUCTIONS 8b210258ca feat(usb-can): add isolated adapter runtime and confirmed CAN transactions
Package the adapter SDK boundary and runtime lifecycle. Confirm admitted CAN transactions, bound retained data and test failure paths with synthetic hardware.
2026-10-29 09:09:59 +03:00

267 lines
10 KiB
Python

"""One isolated native-library owner per USB generation, with bounded RAM."""
import contextlib
import copy
import multiprocessing as mp
import threading
import time
from collections import deque
from datetime import UTC, datetime
from .bridge import Bridges
from .contracts import DEFAULT
from .sdk import SDK
class Engine:
def __init__(self, sdk, clock=time.monotonic, sleep=time.sleep):
self.sdk, self.clock, self.sleep = sdk, clock, sleep
self.configs = [copy.deepcopy(DEFAULT), copy.deepcopy(DEFAULT)]
self.running = [False, False]
self.jobs = [None, None]
self.job_results = [None, None]
self.frames = deque(maxlen=2000)
self.sequence = 0
self.evicted = 0
self.counts = [{"rx": 0, "tx_accepted": 0, "errors": 0} for _ in range(2)]
self.day = datetime.now(UTC).date()
self.error = None
self.bridges = Bridges(self)
def append(self, frame):
self.sequence += 1
if len(self.frames) == self.frames.maxlen:
self.evicted += 1
self.frames.append(
{**frame, "sequence": self.sequence, "observed_at": time.time(), "_mono": self.clock()}
)
def prune(self):
today = datetime.now(UTC).date()
if today != self.day:
self.frames.clear()
self.counts = [{"rx": 0, "tx_accepted": 0, "errors": 0} for _ in range(2)]
self.day = today
while self.frames and self.clock() - self.frames[0]["_mono"] >= 300:
self.frames.popleft()
def receive(self, frame):
ch = frame["channel"]
self.counts[ch]["rx"] += 1
self.counts[ch]["errors"] += int(frame.get("error", False))
self.bridges.receive(frame)
if not self.bridges.occupied(ch):
self.append(frame)
def tick(self):
self.prune()
self.bridges.expire()
for ch in range(2):
if not self.running[ch]:
continue
try:
for frame in self.sdk.receive(ch):
self.receive(frame)
job = self.jobs[ch]
if job and self.clock() >= job["next"]:
plan, index = job["plan"], job["index"]
frame = copy.deepcopy(plan["frames"][index % len(plan["frames"])])
iteration = index // len(plan["frames"])
if plan["increment_id"]:
frame["id"] += iteration
if plan["increment_data"] and frame["data"]:
size = len(frame["data"]) // 2
value = (int(frame["data"], 16) + iteration) % (1 << (8 * size))
frame["data"] = value.to_bytes(size, "big").hex().upper()
self.sdk.transmit(ch, frame)
self.counts[ch]["tx_accepted"] += 1
self.append(
{
**frame,
"channel": ch,
"direction": "TX",
"timestamp_us": None,
"error": False,
"esi": False,
}
)
job["index"] += 1
job["next"] = self.clock() + plan["interval_ms"] / 1000
self.job_results[ch] = {
"state": "running",
"accepted": job["index"],
"total": job["total"],
}
if job["index"] == job["total"]:
self.jobs[ch] = None
self.job_results[ch]["state"] = "complete"
except (OSError, ValueError) as error:
self.error = str(error)[:200]
self.job_results[ch] = {"state": "error", "message": self.error}
self.jobs[ch] = None
self.running[ch] = False
# No retry or automatic restart after uncertain transmission.
self.sdk.stop(ch)
def dispatch(self, action, params):
if action.startswith("bridge."):
return self.bridges.dispatch(action.removeprefix("bridge."), params)
# Vendor USB enumeration can block longer than a bridge poll budget.
# Active channels already have RX error checks; Service.scan independently
# checks the exact sysfs USB generation. Status must remain a RAM snapshot
# while a bridge owns the adapter, without starving its 750 ms lease.
if action == "status" and not self.bridges.claims and not self.sdk.online():
raise OSError("Адаптер не подтвердил связь по USB.")
ch = params.get("channel", 0)
if action != "status" and self.bridges.occupied(ch):
raise ValueError("Канал занят подключением VESC. Измените шину в настройках борта.")
if action == "configure":
if self.running[ch]:
raise ValueError("Остановите канал перед изменением параметров.")
self.configs[ch] = copy.deepcopy(params["config"])
elif action == "start":
if self.running[ch]:
raise ValueError("Канал уже запущен.")
self.sdk.start(ch, self.configs[ch])
self.running[ch] = True
self.error = None
elif action == "stop":
self.jobs[ch] = None
if self.job_results[ch] and self.job_results[ch]["state"] == "running":
self.job_results[ch]["state"] = "cancelled"
self.sdk.stop(ch)
self.running[ch] = False
elif action == "clear":
self.sdk.clear(ch)
self.frames = deque((f for f in self.frames if f["channel"] != ch), maxlen=2000)
self.counts[ch] = {"rx": 0, "tx_accepted": 0, "errors": 0}
elif action == "transmit":
plan = params["plan"]
if not self.running[ch] or self.configs[ch]["mode"] != "normal" or self.jobs[ch]:
raise ValueError("Для передачи нужен свободный канал в обычном режиме.")
if self.configs[ch]["protocol"] == "can" and any(f["fd"] for f in plan["frames"]):
raise ValueError("Канал настроен только на классический CAN.")
self.jobs[ch] = {
"plan": plan,
"index": 0,
"next": self.clock(),
"total": plan["repeat"] * len(plan["frames"]),
}
self.job_results[ch] = {
"state": "running",
"accepted": 0,
"total": self.jobs[ch]["total"],
}
elif action == "transmit.stop":
self.jobs[ch] = None
if self.job_results[ch] and self.job_results[ch]["state"] == "running":
self.job_results[ch]["state"] = "cancelled"
elif action != "status":
raise ValueError("Неизвестная операция.")
self.prune()
after = params.get("after", self.sequence)
frames = [
{k: v for k, v in f.items() if k != "_mono"}
for f in self.frames
if f["sequence"] > after
][:256]
return {
"identity": self.sdk.identity,
"channels": [
{
"index": i,
"owner": "vesc" if self.bridges.occupied(i) else None,
"config": self.configs[i],
"running": self.running[i],
"counts": self.counts[i],
"transmission": self.job_results[i],
}
for i in range(2)
],
"sequence": self.sequence,
"frames": frames,
"evicted": self.evicted,
"oldest_sequence": self.frames[0]["sequence"] if self.frames else self.sequence + 1,
"error": self.error,
"bus_error_counters": None,
"retention_seconds": 300,
"retention_frames": 2000,
}
def run(pipe, index, path):
sdk = None
try:
sdk = SDK(index, path)
engine = Engine(sdk)
pipe.send({"ok": True, "value": engine.dispatch("status", {})})
while True:
if pipe.poll(0.02):
action, params = pipe.recv()
if action == "close":
return
try:
pipe.send({"ok": True, "value": engine.dispatch(action, params)})
except (OSError, ValueError) as error:
pipe.send({"ok": False, "error": str(error)[:300]})
engine.tick()
except (EOFError, BrokenPipeError):
pass
except Exception as error:
with contextlib.suppress(OSError, EOFError):
pipe.send({"ok": False, "error": str(error)[:300]})
finally:
if sdk:
sdk.close()
pipe.close()
class Link:
def __init__(self, index, path):
ctx = mp.get_context("spawn")
self.pipe, child = ctx.Pipe()
self.lock = threading.Lock()
self.process = ctx.Process(target=run, args=(child, index, path), daemon=True)
self.process.start()
child.close()
try:
self.initial = self.result()
except BaseException:
self.close()
raise
@property
def alive(self):
return self.process.is_alive()
def result(self, timeout=6):
if not self.pipe.poll(timeout):
self.close()
raise OSError("SDK не ответил за отведённое время.")
value = self.pipe.recv()
if not value.get("ok"):
raise OSError(value.get("error", "Ошибка SDK."))
return value["value"]
def call(self, action, params):
with self.lock:
if not self.alive:
raise OSError("Сеанс USB завершён.")
self.pipe.send((action, params))
return self.result(.4 if action.startswith("bridge.") else 6)
def close(self):
if self.process.is_alive():
try:
self.pipe.send(("close", {}))
self.process.join(0.25)
except (OSError, EOFError):
pass
if self.process.is_alive():
self.process.terminate()
self.process.join(0.5)
if self.process.is_alive():
self.process.kill()
self.process.join(0.5)
self.pipe.close()