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.
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
VERSION = "0.2.7"
|
||||
MODEL = "waveshare.usb-can-fd-b"
|
||||
SCHEMA = "missioncore.nodedc/plugin-sdk/v0alpha2"
|
||||
@@ -0,0 +1,256 @@
|
||||
"""Private, expiring ownership of CAN channels by the onboard controller service."""
|
||||
|
||||
import binascii
|
||||
import copy
|
||||
import math
|
||||
import struct
|
||||
import uuid
|
||||
from collections import deque
|
||||
|
||||
from .contracts import ARBITRATION, DEFAULT, channel, integer
|
||||
from . import confirmed_tx
|
||||
|
||||
|
||||
def acknowledged_read(frames, receive_id):
|
||||
"""Recognize six exact, argument-free VESC reads for confirmed transmission.
|
||||
|
||||
Waveshare API 2.5: single-shot drops a frame on lost arbitration/error;
|
||||
normal sending retries in the controller. This classifier never admits
|
||||
arbitrary packets, forwarding or writes; exact setters use a separate path. COMM_PING_CAN (62) is the
|
||||
read-only neighbour scan required before control; it needs the same normal
|
||||
arbitration as identity/configuration reads. Closing the claim resets the
|
||||
channel after a failed request; the application never replays a command.
|
||||
"""
|
||||
if len(frames) != 1:
|
||||
return False
|
||||
frame = frames[0]
|
||||
data = bytes.fromhex(frame["data"])
|
||||
return (frame["id"] >> 8 == 8 and frame["id"] & 255 not in (255, receive_id)
|
||||
and len(data) == 3 and data[:2] == bytes((receive_id, 0))
|
||||
and data[2] in (0, 4, 14, 17, 31, 62))
|
||||
|
||||
|
||||
def acknowledged_limits(frames, receive_id):
|
||||
"""Recognize only the pinned Tool's non-storing, non-forwarding limits packet.
|
||||
|
||||
A complete 37-byte COMM_SET_MCCONF_TEMP request is six ordered fragments
|
||||
plus its length/CRC commit. Native Tool validates the configuration before
|
||||
emitting this packet. It requests an ACK and never emits a motor setpoint.
|
||||
Reject classification on any ambiguity; arbitrary writes stay single-shot.
|
||||
"""
|
||||
if len(frames) != 7:
|
||||
return False
|
||||
target = frames[0]["id"] & 255
|
||||
if target in (255, receive_id):
|
||||
return False
|
||||
payload = bytearray()
|
||||
for index, frame in enumerate(frames[:-1]):
|
||||
data = bytes.fromhex(frame["data"])
|
||||
size = 7 if index < 5 else 2
|
||||
if (frame["id"] != (5 << 8) | target or len(data) != size + 1
|
||||
or data[0] != len(payload)):
|
||||
return False
|
||||
payload.extend(data[1:])
|
||||
final = frames[-1]
|
||||
commit = (bytes((receive_id, 0, 0, 37))
|
||||
+ binascii.crc_hqx(payload, 0).to_bytes(2, "big"))
|
||||
if final["id"] != (7 << 8) | target or bytes.fromhex(final["data"]) != commit:
|
||||
return False
|
||||
if payload[:5] != bytes((48, 0, 0, 1, 0)):
|
||||
return False
|
||||
values = struct.unpack(">8f", payload[5:])
|
||||
return (all(math.isfinite(v) for v in values)
|
||||
and all(0 < scale <= 1 for scale in values[:2]))
|
||||
|
||||
|
||||
def acknowledged_configuration(frames, receive_id):
|
||||
"""Recognize one complete native configuration write and its exact ACK code.
|
||||
|
||||
Motor/application configurations use the ordinary VESC fragmented transport,
|
||||
including the two-byte offset after byte 255. The native Tool owns schema
|
||||
validation and write admission; this boundary checks destination, contiguous
|
||||
framing, length and CRC before permitting CAN-controller arbitration retry.
|
||||
It never retries the application command or admits forwarded/broadcast writes.
|
||||
"""
|
||||
if len(frames) < 2:
|
||||
return None
|
||||
target = frames[0]["id"] & 255
|
||||
if target in (255, receive_id):
|
||||
return None
|
||||
payload = bytearray()
|
||||
for index, frame in enumerate(frames[:-1]):
|
||||
width, size, code = (1, 7, 5) if len(payload) <= 255 else (2, 6, 6)
|
||||
data = bytes.fromhex(frame["data"])
|
||||
if (frame["id"] != (code << 8) | target or not width < len(data) <= width + size
|
||||
or int.from_bytes(data[:width], "big") != len(payload)
|
||||
or (index < len(frames) - 2 and len(data) != width + size)):
|
||||
return None
|
||||
payload.extend(data[width:])
|
||||
if len(payload) > 10000:
|
||||
return None
|
||||
if len(payload) < 7 or payload[0] not in (13, 16):
|
||||
return None
|
||||
commit = (bytes((receive_id, 0)) + len(payload).to_bytes(2, "big")
|
||||
+ binascii.crc_hqx(payload, 0).to_bytes(2, "big"))
|
||||
if frames[-1]["id"] != (7 << 8) | target or bytes.fromhex(frames[-1]["data"]) != commit:
|
||||
return None
|
||||
return payload[0]
|
||||
|
||||
|
||||
class Bridges:
|
||||
def __init__(self, engine):
|
||||
self.e = engine
|
||||
self.claims = {}
|
||||
self.previous = {}
|
||||
|
||||
def occupied(self, ch):
|
||||
return any(c["channel"] == ch for c in self.claims.values())
|
||||
|
||||
def close(self, token):
|
||||
claim = self.claims.pop(token, None)
|
||||
if claim and (claim["write_pending"] is not None or claim["tx_pending"]):
|
||||
# A write without its exact ACK may still be queued in the adapter.
|
||||
# Retire every shared claim before resetting the channel; another
|
||||
# reader must not keep a timed-out mutation alive in hardware.
|
||||
for other, value in list(self.claims.items()):
|
||||
if value["channel"] == claim["channel"]:
|
||||
self.claims.pop(other)
|
||||
if claim and not self.occupied(claim["channel"]):
|
||||
ch = claim["channel"]
|
||||
self.e.running[ch] = False
|
||||
self.e.configs[ch] = self.previous.pop(ch, copy.deepcopy(DEFAULT))
|
||||
self.e.sdk.stop(ch)
|
||||
|
||||
def expire(self):
|
||||
for token, claim in list(self.claims.items()):
|
||||
if self.e.clock() >= claim["until"]:
|
||||
self.close(token)
|
||||
|
||||
def receive(self, frame):
|
||||
for claim in self.claims.values():
|
||||
if (
|
||||
frame["channel"] == claim["channel"]
|
||||
and frame.get("extended")
|
||||
and frame["id"] & 255 == claim["receive_id"]
|
||||
):
|
||||
pending = claim["write_pending"]
|
||||
if (pending is not None and frame["id"] >> 8 == 8
|
||||
and not any(frame.get(k) for k in ("fd", "rtr", "error"))
|
||||
and frame.get("data", "").lower()
|
||||
== bytes((pending["target"], 1, pending["command"])).hex()):
|
||||
claim["write_pending"] = None
|
||||
if len(claim["frames"]) == 512:
|
||||
claim["error"] = "Переполнение CAN. Сеанс требует повторного подключения."
|
||||
claim["frames"].append(frame)
|
||||
|
||||
def dispatch(self, action, p):
|
||||
self.expire()
|
||||
e = self.e
|
||||
if action == "open":
|
||||
if set(p) != {"channel", "bitrate", "receive_id"}:
|
||||
raise ValueError("Invalid bridge configuration")
|
||||
ch, bitrate = channel(p["channel"]), p["bitrate"]
|
||||
receive_id = integer(p["receive_id"], 0, 254)
|
||||
if type(bitrate) is not int or bitrate not in ARBITRATION:
|
||||
raise ValueError("Unsupported CAN bitrate")
|
||||
if len(self.claims) >= 8 or any(
|
||||
c["channel"] == ch and c["receive_id"] == receive_id for c in self.claims.values()
|
||||
):
|
||||
raise ValueError("Адрес ответа CAN уже занят.")
|
||||
if self.occupied(ch):
|
||||
if e.configs[ch]["bitrate"] != bitrate:
|
||||
raise ValueError("На одном канале нужна одна скорость CAN.")
|
||||
else:
|
||||
if e.running[ch] or e.jobs[ch]:
|
||||
raise ValueError(
|
||||
"Остановите ручную работу CAN-канала перед подключением привода."
|
||||
)
|
||||
config = {**copy.deepcopy(DEFAULT), "mode": "normal", "bitrate": bitrate}
|
||||
e.sdk.start(ch, config)
|
||||
self.previous[ch] = e.configs[ch]
|
||||
e.configs[ch], e.running[ch] = config, True
|
||||
token = uuid.uuid4().hex
|
||||
self.claims[token] = {
|
||||
"channel": ch,
|
||||
"receive_id": receive_id,
|
||||
"until": e.clock() + 0.75,
|
||||
"frames": deque(maxlen=512),
|
||||
"error": None,
|
||||
"write_pending": None,
|
||||
"tx_pending": False,
|
||||
"tx_confirmation": {"kind": "adapter_echo", "confirmed": 0, "elapsed_ms": None},
|
||||
}
|
||||
return {"token": token}
|
||||
token = p.get("token")
|
||||
claim = self.claims.get(token)
|
||||
if not claim:
|
||||
raise ValueError("Сеанс CAN завершён. Автоматическая передача не возобновляется.")
|
||||
if action == "close":
|
||||
self.close(token)
|
||||
return {}
|
||||
if claim["error"] or not e.running[claim["channel"]]:
|
||||
self.close(token)
|
||||
raise ValueError(claim["error"] or "CAN-канал остановлен.")
|
||||
claim["until"] = e.clock() + 0.75
|
||||
if action == "send":
|
||||
frames, deadline = p.get("frames"), p.get("deadline")
|
||||
if (
|
||||
type(deadline) not in (int, float)
|
||||
or not math.isfinite(deadline)
|
||||
or not e.clock() < deadline <= e.clock() + 0.3
|
||||
or not isinstance(frames, list)
|
||||
or not 1 <= len(frames) <= 2048
|
||||
):
|
||||
raise ValueError("Передача CAN устарела или превышает предел.")
|
||||
for frame in frames:
|
||||
if (
|
||||
set(frame) != {"id", "data"}
|
||||
or type(frame["id"]) is not int
|
||||
or not 0 <= frame["id"] <= 0x1FFFFFFF
|
||||
or not isinstance(frame["data"], str)
|
||||
or not 1 <= len(bytes.fromhex(frame["data"])) <= 8
|
||||
):
|
||||
raise ValueError("Invalid classic CAN frame")
|
||||
if claim["write_pending"] is not None:
|
||||
self.close(token)
|
||||
raise ValueError(
|
||||
"Подтверждение записи не получено; CAN-сеанс закрыт."
|
||||
)
|
||||
ack_command = (48 if acknowledged_limits(frames, claim["receive_id"])
|
||||
else acknowledged_configuration(frames, claim["receive_id"]))
|
||||
confirm = (acknowledged_read(frames, claim["receive_id"])
|
||||
or confirmed_tx.output_frame(frames, claim["receive_id"]))
|
||||
send_type = 0 if ack_command is not None else 1
|
||||
if ack_command is not None:
|
||||
claim["write_pending"] = {"target": frames[0]["id"] & 255, "command": ack_command}
|
||||
try:
|
||||
for frame in frames:
|
||||
if e.clock() >= deadline:
|
||||
raise ValueError("Срок передачи CAN истёк; повтор запрещён.")
|
||||
value = {
|
||||
**frame,
|
||||
"extended": True,
|
||||
"fd": False,
|
||||
"rtr": False,
|
||||
"brs": False,
|
||||
"dlc": len(frame["data"]) // 2,
|
||||
"send_type": send_type,
|
||||
}
|
||||
if confirm:
|
||||
claim["tx_pending"] = True
|
||||
confirmed_tx.send(e, claim, value, deadline)
|
||||
claim["tx_pending"] = False
|
||||
else:
|
||||
e.sdk.transmit(claim["channel"], value)
|
||||
e.counts[claim["channel"]]["tx_accepted"] += 1
|
||||
except (OSError, ValueError):
|
||||
self.close(token)
|
||||
raise
|
||||
elif action != "poll":
|
||||
raise ValueError("Unknown bridge action")
|
||||
frames = list(claim["frames"])
|
||||
claim["frames"].clear()
|
||||
result = {"frames": frames}
|
||||
if action == "send" and confirm:
|
||||
result["tx_confirmation"] = dict(claim["tx_confirmation"])
|
||||
return result
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Stop-and-wait CAN transmission; an adapter echo is not a VESC command ACK."""
|
||||
|
||||
# Bound the adapter's normal arbitration retries inside the caller's deadline.
|
||||
# One frame may be outstanding. Timeout retires the whole shared channel.
|
||||
ECHO_TIMEOUT = 0.040
|
||||
|
||||
|
||||
def output_frame(frames, receive_id):
|
||||
"""Exact non-forwarded native setters and the existing 250 ms PPM lease."""
|
||||
if len(frames) != 1:
|
||||
return False
|
||||
frame = frames[0]
|
||||
data = bytes.fromhex(frame["data"])
|
||||
if (frame["id"] >> 8 != 8 or frame["id"] & 255 in (receive_id, 255)
|
||||
or data[:2] != bytes((receive_id, 0))):
|
||||
return False
|
||||
payload = data[2:]
|
||||
return ((len(payload) == 5 and payload[0] in (5, 6, 8))
|
||||
or payload == bytes((63, 0, 0, 0, 0, 250)))
|
||||
|
||||
|
||||
def matches(frame, sent, channel):
|
||||
return (frame.get("channel") == channel and frame.get("id") == sent["id"]
|
||||
and frame.get("extended") is True
|
||||
and not any(frame.get(k) for k in ("fd", "rtr", "error"))
|
||||
and frame.get("dlc") == sent["dlc"]
|
||||
and frame.get("data", "").lower() == sent["data"].lower())
|
||||
|
||||
|
||||
def send(engine, claim, frame, deadline):
|
||||
"""Submit once; normal+self-reception retries are owned by the CAN controller.
|
||||
|
||||
The caller must reset the entire shared channel on ANY failure, including
|
||||
exceptions after SDK acceptance. Never replay or fall back to single-shot.
|
||||
Drain before submission so buffered echoes cannot acknowledge a new request.
|
||||
Every previous confirmed request consumed exactly one echo (no app retries).
|
||||
Unrelated RX is routed normally, including traffic for other shared claims.
|
||||
"""
|
||||
channel = claim["channel"]
|
||||
until = min(deadline, engine.clock() + ECHO_TIMEOUT)
|
||||
while True:
|
||||
if engine.clock() >= until:
|
||||
raise OSError("Истёк срок подтверждения передачи CAN.")
|
||||
received = engine.sdk.receive(channel)
|
||||
for rx in received:
|
||||
engine.receive(rx)
|
||||
if rx.get("error"):
|
||||
raise OSError("Ошибка CAN перед отправкой команды.")
|
||||
if not received:
|
||||
break
|
||||
started = engine.clock()
|
||||
engine.sdk.transmit(channel, {**frame, "send_type": 2})
|
||||
engine.counts[channel]["tx_accepted"] += 1
|
||||
while engine.clock() < until:
|
||||
received = engine.sdk.receive(channel)
|
||||
confirmed = False
|
||||
for rx in received:
|
||||
engine.receive(rx)
|
||||
if rx.get("error"):
|
||||
raise OSError("Ошибка CAN при подтверждении передачи.")
|
||||
confirmed = confirmed or matches(rx, frame, channel)
|
||||
if confirmed and engine.clock() < until:
|
||||
elapsed = (engine.clock() - started) * 1000
|
||||
claim["tx_confirmation"] = {
|
||||
"kind": "adapter_echo", "confirmed": claim["tx_confirmation"]["confirmed"] + 1,
|
||||
"elapsed_ms": elapsed,
|
||||
}
|
||||
return
|
||||
# Injectable sleep keeps the deadline tests deterministic.
|
||||
engine.sleep(min(0.001, max(0, until - engine.clock())))
|
||||
raise OSError("Адаптер не подтвердил передачу CAN в срок; канал остановлен.")
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Validated public contract. No imported configuration can start a channel."""
|
||||
|
||||
import copy
|
||||
import re
|
||||
|
||||
ARBITRATION = (50000, 100000, 125000, 250000, 500000, 800000, 1000000)
|
||||
DATA_RATES = (100000, 125000, 250000, 500000, 800000, 1000000, 2000000, 4000000, 5000000)
|
||||
DEFAULT = {
|
||||
"protocol": "can",
|
||||
"mode": "listen",
|
||||
"bitrate": 500000,
|
||||
"data_bitrate": 2000000,
|
||||
"standard": "iso",
|
||||
"filters": [],
|
||||
}
|
||||
ACTIONS = frozenset(
|
||||
(
|
||||
"details",
|
||||
"verify",
|
||||
"can.status",
|
||||
"can.configure",
|
||||
"can.start",
|
||||
"can.stop",
|
||||
"can.clear",
|
||||
"can.transmit.preview",
|
||||
"can.transmit.apply",
|
||||
"can.transmit.stop",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def integer(value, low, high):
|
||||
if type(value) is not int or not low <= value <= high:
|
||||
raise ValueError("Число вне допустимого диапазона.")
|
||||
return value
|
||||
|
||||
|
||||
def channel(value):
|
||||
return integer(value, 0, 1)
|
||||
|
||||
|
||||
def configuration(value):
|
||||
if not isinstance(value, dict) or set(value) != set(DEFAULT):
|
||||
raise ValueError("Неверный состав конфигурации CAN.")
|
||||
if value["protocol"] not in ("can", "fd") or value["mode"] not in ("listen", "normal"):
|
||||
raise ValueError("Неизвестный режим CAN.")
|
||||
if type(value["bitrate"]) is not int or value["bitrate"] not in ARBITRATION:
|
||||
raise ValueError("Неподдерживаемая скорость арбитража.")
|
||||
if type(value["data_bitrate"]) is not int or value["data_bitrate"] not in DATA_RATES:
|
||||
raise ValueError("Неподдерживаемая скорость данных.")
|
||||
if value["standard"] not in ("iso", "bosch"):
|
||||
raise ValueError("Неизвестный стандарт CAN FD.")
|
||||
filters = value["filters"]
|
||||
if not isinstance(filters, list) or len(filters) > 64:
|
||||
raise ValueError("Слишком много фильтров.")
|
||||
weight = 0
|
||||
for item in filters:
|
||||
if (
|
||||
not isinstance(item, dict)
|
||||
or set(item) != {"extended", "start", "end"}
|
||||
or type(item["extended"]) is not bool
|
||||
):
|
||||
raise ValueError("Неверный фильтр.")
|
||||
limit = 0x1FFFFFFF if item["extended"] else 0x7FF
|
||||
integer(item["start"], 0, limit)
|
||||
integer(item["end"], item["start"], limit)
|
||||
weight += 2 if item["extended"] else 1
|
||||
if weight > 64:
|
||||
raise ValueError("До 64 стандартных или 32 расширенных диапазонов.")
|
||||
return copy.deepcopy(value)
|
||||
|
||||
|
||||
def frame(value):
|
||||
keys = {"id", "extended", "fd", "rtr", "brs", "data", "dlc", "send_type"}
|
||||
if not isinstance(value, dict) or set(value) != keys:
|
||||
raise ValueError("Неверный состав CAN-кадра.")
|
||||
for flag in ("extended", "fd", "rtr", "brs"):
|
||||
if type(value[flag]) is not bool:
|
||||
raise ValueError("Неверный флаг CAN.")
|
||||
integer(value["id"], 0, 0x1FFFFFFF if value["extended"] else 0x7FF)
|
||||
integer(value["send_type"], 0, 3)
|
||||
integer(value["dlc"], 0, 64 if value["fd"] else 8)
|
||||
if value["fd"] and value["dlc"] not in (*range(9), 12, 16, 20, 24, 32, 48, 64):
|
||||
raise ValueError("Недопустимая длина CAN FD.")
|
||||
if (value["fd"] and value["rtr"]) or (value["brs"] and not value["fd"]):
|
||||
raise ValueError("Несовместимые флаги CAN.")
|
||||
data = value["data"]
|
||||
if not isinstance(data, str) or not re.fullmatch(r"[0-9a-fA-F]{0,128}", data) or len(data) % 2:
|
||||
raise ValueError("Данные должны быть шестнадцатеричными байтами.")
|
||||
if len(data) // 2 != (0 if value["rtr"] else value["dlc"]):
|
||||
raise ValueError("Длина данных не совпадает с DLC.")
|
||||
return {**value, "data": data.upper()}
|
||||
|
||||
|
||||
def transmission(value):
|
||||
if not isinstance(value, dict) or set(value) != {
|
||||
"frames",
|
||||
"repeat",
|
||||
"interval_ms",
|
||||
"increment_id",
|
||||
"increment_data",
|
||||
}:
|
||||
raise ValueError("Неверное задание передачи.")
|
||||
frames = value["frames"]
|
||||
if not isinstance(frames, list) or not 1 <= len(frames) <= 64:
|
||||
raise ValueError("В задании должно быть от 1 до 64 кадров.")
|
||||
frames = [frame(item) for item in frames]
|
||||
repeat = integer(value["repeat"], 1, 1000)
|
||||
interval = integer(value["interval_ms"], 10, 60000)
|
||||
if repeat * len(frames) > 1000 or (repeat * len(frames) - 1) * interval > 60000:
|
||||
raise ValueError("Одно задание: до 1000 кадров и 60 секунд.")
|
||||
for key in ("increment_id", "increment_data"):
|
||||
if type(value[key]) is not bool:
|
||||
raise ValueError("Неверный режим инкремента.")
|
||||
if value["increment_id"]:
|
||||
for item in frames:
|
||||
integer(item["id"] + repeat - 1, 0, 0x1FFFFFFF if item["extended"] else 0x7FF)
|
||||
return {**value, "frames": frames}
|
||||
@@ -0,0 +1,49 @@
|
||||
"""VID/PID/product discovery; a USB descriptor is not the protocol serial."""
|
||||
|
||||
import hashlib
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def device_id(value):
|
||||
return "usbcan_" + hashlib.sha256(value.encode()).hexdigest()[:32]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Attachment:
|
||||
binding: str
|
||||
usb: str
|
||||
path: str
|
||||
speed: str
|
||||
|
||||
@property
|
||||
def id(self):
|
||||
return device_id("provisional:" + self.binding)
|
||||
|
||||
|
||||
def discover(root=Path("/sys/bus/usb/devices")):
|
||||
result = []
|
||||
for path in sorted(root.glob("*")):
|
||||
try:
|
||||
|
||||
def read(name, path=path):
|
||||
return (path / name).read_text().strip()
|
||||
|
||||
if (read("idVendor"), read("idProduct"), read("product")) != (
|
||||
"04d8",
|
||||
"0053",
|
||||
"USB CANFD DEBUG",
|
||||
):
|
||||
continue
|
||||
bus, dev = int(read("busnum")), int(read("devnum"))
|
||||
result.append(
|
||||
Attachment(
|
||||
path.name + ":" + str(dev),
|
||||
path.name,
|
||||
f"/dev/bus/usb/{bus:03}/{dev:03}",
|
||||
read("speed") + " Мбит/с",
|
||||
)
|
||||
)
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
return result[:8]
|
||||
@@ -0,0 +1,294 @@
|
||||
"""Exact packed ABI from the pinned Waveshare x86-64 header; no demo execution."""
|
||||
|
||||
import contextlib
|
||||
import ctypes as C
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
U8, U16, U32, U64, PTR = C.c_uint8, C.c_uint16, C.c_uint32, C.c_uint64, C.c_void_p
|
||||
|
||||
|
||||
class Packed(C.Structure):
|
||||
_pack_ = 1
|
||||
|
||||
|
||||
class DeviceInfo(Packed):
|
||||
_fields_ = [(name, U16) for name in ("hardware", "firmware", "driver", "interface", "irq")] + [
|
||||
("channels", U8),
|
||||
("serial", U8 * 21),
|
||||
("model", U8 * 40),
|
||||
("reserved", U16 * 5),
|
||||
]
|
||||
|
||||
|
||||
class Classic(Packed):
|
||||
_fields_ = [
|
||||
("id", U32),
|
||||
("length", U8),
|
||||
("flags", U8),
|
||||
("res0", U8),
|
||||
("res1", U8),
|
||||
("data", U8 * 8),
|
||||
]
|
||||
|
||||
|
||||
class FD(Packed):
|
||||
_fields_ = [
|
||||
("id", U32),
|
||||
("length", U8),
|
||||
("flags", U8),
|
||||
("res0", U8),
|
||||
("res1", U8),
|
||||
("data", U8 * 64),
|
||||
]
|
||||
|
||||
|
||||
class InitClassic(Packed):
|
||||
_fields_ = [
|
||||
("code", U32),
|
||||
("mask", U32),
|
||||
("reserved", U32),
|
||||
("filter", U8),
|
||||
("timing0", U8),
|
||||
("timing1", U8),
|
||||
("mode", U8),
|
||||
]
|
||||
|
||||
|
||||
class InitFD(Packed):
|
||||
_fields_ = [
|
||||
("code", U32),
|
||||
("mask", U32),
|
||||
("abit", U32),
|
||||
("dbit", U32),
|
||||
("brp", U32),
|
||||
("filter", U8),
|
||||
("mode", U8),
|
||||
("pad", U16),
|
||||
("reserved", U32),
|
||||
]
|
||||
|
||||
|
||||
class InitUnion(C.Union):
|
||||
_pack_ = 1
|
||||
_fields_ = [("classic", InitClassic), ("fd", InitFD)]
|
||||
|
||||
|
||||
class Init(Packed):
|
||||
_fields_ = [("type", U32), ("config", InitUnion)]
|
||||
|
||||
|
||||
class Tx(Packed):
|
||||
_fields_ = [("frame", Classic), ("send_type", U32)]
|
||||
|
||||
|
||||
class TxFD(Packed):
|
||||
_fields_ = [("frame", FD), ("send_type", U32)]
|
||||
|
||||
|
||||
class Rx(Packed):
|
||||
_fields_ = [("frame", Classic), ("timestamp", U64)]
|
||||
|
||||
|
||||
class RxFD(Packed):
|
||||
_fields_ = [("frame", FD), ("timestamp", U64)]
|
||||
|
||||
|
||||
SIZES = {DeviceInfo: 82, Classic: 16, FD: 72, Init: 32, Tx: 20, TxFD: 76, Rx: 24, RxFD: 80}
|
||||
|
||||
|
||||
def check_abi():
|
||||
for cls, size in SIZES.items():
|
||||
if C.sizeof(cls) != size:
|
||||
raise RuntimeError("SDK ABI mismatch: " + cls.__name__)
|
||||
|
||||
|
||||
def library(path="/usr/lib/mission-core-usb-can/sdk/libcontrolcanfd.so"):
|
||||
check_abi()
|
||||
lib = C.CDLL(path)
|
||||
signatures = {
|
||||
"OpenDevice": (PTR, [U32, U32, U32]),
|
||||
"CloseDevice": (U32, [PTR]),
|
||||
"GetDeviceInf": (U32, [PTR, C.POINTER(DeviceInfo)]),
|
||||
"IsDeviceOnLine": (U32, [PTR]),
|
||||
"InitCAN": (PTR, [PTR, U32, C.POINTER(Init)]),
|
||||
"GetReceiveNum": (U32, [PTR, U8]),
|
||||
"SetBaudRateCustom": (U32, [PTR, U32, C.c_char_p]),
|
||||
}
|
||||
for name in ("StartCAN", "ResetCAN", "ClearBuffer", "ClearFilter", "AckFilter"):
|
||||
signatures[name] = (U32, [PTR])
|
||||
for name in ("SetAbitBaud", "SetDbitBaud", "SetCANFDStandard"):
|
||||
signatures[name] = (U32, [PTR, U32, U32])
|
||||
for name in ("SetFilterMode", "SetFilterStartID", "SetFilterEndID"):
|
||||
signatures[name] = (U32, [PTR, U32])
|
||||
for suffix, tx, rx in (("", Tx, Rx), ("FD", TxFD, RxFD)):
|
||||
signatures["Transmit" + suffix] = (U32, [PTR, C.POINTER(tx), U32])
|
||||
signatures["Receive" + suffix] = (U32, [PTR, C.POINTER(rx), U32, C.c_int])
|
||||
for name, (result, args) in signatures.items():
|
||||
fn = getattr(lib, "ZCAN_" + name)
|
||||
fn.restype, fn.argtypes = result, args
|
||||
return lib
|
||||
|
||||
|
||||
def text(value):
|
||||
return bytes(value).split(b"\0", 1)[0].decode("ascii", "strict").strip()
|
||||
|
||||
|
||||
def version(value):
|
||||
return f"{value >> 8:X}.{value & 255:02X}"
|
||||
|
||||
|
||||
class SDK:
|
||||
def __init__(self, index, expected_usb, lib=None):
|
||||
self.lib = lib or library()
|
||||
self.handle, self.handles = None, [None, None]
|
||||
self.handle = self.lib.ZCAN_OpenDevice(41, index, 0)
|
||||
if not self.handle:
|
||||
raise OSError("Не удалось открыть USB-CAN. Проверьте доступ и другие программы.")
|
||||
try:
|
||||
# SDK selects by index. Prove its actual open device before assigning
|
||||
# a physical session; USB port order is never hardware identity.
|
||||
opened = set()
|
||||
for entry in Path("/proc/self/fd").iterdir():
|
||||
try:
|
||||
target = os.readlink(entry)
|
||||
if target.startswith("/dev/bus/usb/"):
|
||||
opened.add(target)
|
||||
except OSError:
|
||||
pass
|
||||
if opened != {expected_usb}:
|
||||
raise OSError("SDK не подтвердил однозначное соответствие USB-устройству.")
|
||||
info = DeviceInfo()
|
||||
self.ok(self.lib.ZCAN_GetDeviceInf(self.handle, C.byref(info)), "идентификация")
|
||||
serial = text(info.serial)
|
||||
if not serial or len(serial) > 20 or info.channels != 2:
|
||||
raise OSError("Не подтверждены серийный номер и два CAN-канала.")
|
||||
self.identity = {
|
||||
"serial": serial,
|
||||
"model": text(info.model),
|
||||
"channels": int(info.channels),
|
||||
**{
|
||||
key: version(getattr(info, key))
|
||||
for key in ("hardware", "firmware", "driver", "interface")
|
||||
},
|
||||
}
|
||||
except BaseException:
|
||||
self.close()
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def ok(value, operation):
|
||||
if value != 1:
|
||||
raise OSError("SDK отклонил операцию: " + operation)
|
||||
|
||||
def start(self, channel, config):
|
||||
self.stop(channel)
|
||||
self.ok(
|
||||
self.lib.ZCAN_SetAbitBaud(self.handle, channel, config["bitrate"]), "скорость арбитража"
|
||||
)
|
||||
self.ok(
|
||||
self.lib.ZCAN_SetDbitBaud(self.handle, channel, config["data_bitrate"]),
|
||||
"скорость данных",
|
||||
)
|
||||
self.ok(
|
||||
self.lib.ZCAN_SetCANFDStandard(
|
||||
self.handle, channel, int(config["standard"] == "bosch")
|
||||
),
|
||||
"стандарт FD",
|
||||
)
|
||||
init = Init()
|
||||
# The CAN-FD controller uses its FD init structure for classical frames
|
||||
# too; protocol selection governs allowed TX/RX frame formats.
|
||||
init.type = 1
|
||||
init.config.fd.mode = int(config["mode"] == "listen")
|
||||
init.config.fd.mask = 0xFFFFFFFF
|
||||
handle = self.lib.ZCAN_InitCAN(self.handle, channel, C.byref(init))
|
||||
if not handle:
|
||||
raise OSError("SDK не инициализировал CAN-канал.")
|
||||
self.handles[channel] = handle
|
||||
try:
|
||||
self.ok(self.lib.ZCAN_ClearFilter(handle), "очистка фильтров")
|
||||
# Explicit full ranges when no filter was requested.
|
||||
for item in config["filters"] or [
|
||||
{"extended": False, "start": 0, "end": 0x7FF},
|
||||
{"extended": True, "start": 0, "end": 0x1FFFFFFF},
|
||||
]:
|
||||
self.ok(self.lib.ZCAN_SetFilterMode(handle, int(item["extended"])), "тип фильтра")
|
||||
self.ok(self.lib.ZCAN_SetFilterStartID(handle, item["start"]), "начало фильтра")
|
||||
self.ok(self.lib.ZCAN_SetFilterEndID(handle, item["end"]), "конец фильтра")
|
||||
self.ok(self.lib.ZCAN_AckFilter(handle), "применение фильтров")
|
||||
self.ok(self.lib.ZCAN_StartCAN(handle), "запуск канала")
|
||||
except BaseException:
|
||||
self.stop(channel)
|
||||
raise
|
||||
|
||||
def stop(self, channel):
|
||||
handle = self.handles[channel]
|
||||
if handle:
|
||||
self.ok(self.lib.ZCAN_ResetCAN(handle), "остановка канала")
|
||||
self.handles[channel] = None
|
||||
|
||||
def clear(self, channel):
|
||||
if self.handles[channel]:
|
||||
self.ok(self.lib.ZCAN_ClearBuffer(self.handles[channel]), "очистка приёмного буфера")
|
||||
|
||||
def receive(self, channel):
|
||||
handle = self.handles[channel]
|
||||
if not handle:
|
||||
return []
|
||||
frames = []
|
||||
for fd, cls, method in (
|
||||
(False, Rx, self.lib.ZCAN_Receive),
|
||||
(True, RxFD, self.lib.ZCAN_ReceiveFD),
|
||||
):
|
||||
data = (cls * 64)()
|
||||
count = method(handle, data, 64, 0)
|
||||
if count > 64:
|
||||
raise OSError("SDK вернул ошибку чтения CAN.")
|
||||
for item in data[:count]:
|
||||
f = item.frame
|
||||
if f.length > (64 if fd else 8):
|
||||
raise OSError("SDK вернул повреждённый CAN-кадр.")
|
||||
frames.append(
|
||||
{
|
||||
"channel": channel,
|
||||
"direction": "RX",
|
||||
"timestamp_us": int(item.timestamp),
|
||||
"id": int(f.id & 0x1FFFFFFF),
|
||||
"extended": bool(f.id & 0x80000000),
|
||||
"rtr": bool(f.id & 0x40000000),
|
||||
"error": bool(f.id & 0x20000000),
|
||||
"fd": fd,
|
||||
"brs": bool(f.flags & 1) if fd else False,
|
||||
"esi": bool(f.flags & 2) if fd else False,
|
||||
"dlc": int(f.length),
|
||||
"data": bytes(f.data[: f.length]).hex().upper(),
|
||||
}
|
||||
)
|
||||
return frames
|
||||
|
||||
def transmit(self, channel, frame):
|
||||
if not self.handles[channel]:
|
||||
raise ValueError("Канал остановлен.")
|
||||
value = TxFD() if frame["fd"] else Tx()
|
||||
value.frame.id = frame["id"] | (int(frame["extended"]) << 31) | (int(frame["rtr"]) << 30)
|
||||
value.frame.length = frame["dlc"]
|
||||
value.frame.flags = int(frame["brs"]) if frame["fd"] else 0
|
||||
data = bytes.fromhex(frame["data"])
|
||||
for index, byte in enumerate(data):
|
||||
value.frame.data[index] = byte
|
||||
value.send_type = frame["send_type"]
|
||||
fn = self.lib.ZCAN_TransmitFD if frame["fd"] else self.lib.ZCAN_Transmit
|
||||
self.ok(fn(self.handles[channel], C.byref(value), 1), "передача кадра")
|
||||
|
||||
def online(self):
|
||||
# SDK's documented STATUS_ONLINE is 2, not STATUS_OK (1).
|
||||
return self.lib.ZCAN_IsDeviceOnLine(self.handle) == 2
|
||||
|
||||
def close(self):
|
||||
if self.handle:
|
||||
for channel in range(2):
|
||||
with contextlib.suppress(OSError):
|
||||
self.stop(channel)
|
||||
self.lib.ZCAN_CloseDevice(self.handle)
|
||||
self.handle = None
|
||||
@@ -0,0 +1,198 @@
|
||||
"""Private local USB-CAN API. No channel opens during service startup."""
|
||||
|
||||
import contextlib
|
||||
import json
|
||||
import os
|
||||
import pwd
|
||||
import re
|
||||
import socket
|
||||
import socketserver
|
||||
import struct
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler
|
||||
from pathlib import Path
|
||||
|
||||
from .service import Service
|
||||
try:
|
||||
from .maintenance import Maintenance # Same SDK file copied by payload.py.
|
||||
except ModuleNotFoundError: # Source checkout, never needed on installed Node.
|
||||
import runpy
|
||||
Maintenance = runpy.run_path(str(Path(__file__).resolve().parents[3] /
|
||||
"packages/plugin-sdk/python/missioncore_plugin_sdk/maintenance.py"))["Maintenance"]
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
self.dispatch()
|
||||
|
||||
def do_POST(self):
|
||||
self.dispatch()
|
||||
|
||||
def dispatch(self):
|
||||
_, uid, _ = struct.unpack("3i", self.connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
|
||||
if uid == 0:
|
||||
result = None
|
||||
if self.command == "POST" and self.path == "/maintenance/enter":
|
||||
result = self.server.maintenance.enter(self.server.idle, self.server.quiesce)
|
||||
elif self.command == "POST" and self.path == "/maintenance/leave":
|
||||
try: result = self.server.maintenance.leave()
|
||||
except ValueError: result = {"resumed": False}
|
||||
elif self.command == "GET" and self.path == "/prepare-safe":
|
||||
result = {"safe": self.server.idle() is None}
|
||||
if result is not None:
|
||||
data = json.dumps(result).encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
return
|
||||
self.send_error(403)
|
||||
return
|
||||
with self.server.maintenance.work() as admitted:
|
||||
if not admitted:
|
||||
self.send_error(503, "Device service is under maintenance")
|
||||
return
|
||||
self.dispatch_admitted()
|
||||
|
||||
def dispatch_admitted(self):
|
||||
self.connection.settimeout(10)
|
||||
status = 200
|
||||
try:
|
||||
_, uid, _ = struct.unpack(
|
||||
"3i", self.connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)
|
||||
)
|
||||
if self.command == "GET" and self.path == "/prepare-safe" and uid == 0:
|
||||
result = {"safe": self.server.service.prepare_safe()}
|
||||
elif uid == self.server.vesc_uid and self.path in ("/bridge", "/bridge-inventory"):
|
||||
if self.headers.get("Transfer-Encoding"):
|
||||
raise ValueError("Invalid bridge request")
|
||||
if self.command == "GET" and self.path == "/bridge-inventory":
|
||||
result = self.server.service.bridge_inventory()
|
||||
elif self.command == "POST" and self.path == "/bridge":
|
||||
size = int(self.headers.get("Content-Length", "0"))
|
||||
if (
|
||||
not 0 < size <= 196608
|
||||
or self.headers.get("Content-Type") != "application/json"
|
||||
):
|
||||
raise ValueError("Invalid bridge request")
|
||||
raw = self.rfile.read(size)
|
||||
if len(raw) != size:
|
||||
raise ValueError("Incomplete bridge request")
|
||||
result = self.server.service.bridge(json.loads(raw))
|
||||
else:
|
||||
raise ValueError("Invalid bridge method")
|
||||
else:
|
||||
node = self.headers.get("X-Node-Id", "")
|
||||
if (
|
||||
uid != self.server.node_uid
|
||||
or not re.fullmatch(r"[a-zA-Z0-9_.:-]{1,128}", node)
|
||||
or self.headers.get("Transfer-Encoding")
|
||||
):
|
||||
raise ValueError("Недопустимый запрос.")
|
||||
if self.command == "GET" and self.path == "/inventory":
|
||||
result = self.server.service.inventory(node)
|
||||
elif self.command == "POST" and self.path == "/operation":
|
||||
size = int(self.headers.get("Content-Length", "0"))
|
||||
if (
|
||||
not 0 < size <= 65536
|
||||
or self.headers.get("Content-Type") != "application/json"
|
||||
):
|
||||
raise ValueError("Неверный размер запроса.")
|
||||
raw = self.rfile.read(size)
|
||||
if len(raw) != size:
|
||||
raise ValueError("Неполный запрос.")
|
||||
result = self.server.service.execute(json.loads(raw))
|
||||
else:
|
||||
raise ValueError("Неизвестный запрос.")
|
||||
except (ValueError, KeyError, TypeError, OSError) as error:
|
||||
status, result = 400, {"error": str(error)[:300]}
|
||||
data = json.dumps(result, ensure_ascii=False, allow_nan=False).encode()
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
|
||||
|
||||
class Server(socketserver.ThreadingMixIn, socketserver.UnixStreamServer):
|
||||
daemon_threads = True
|
||||
|
||||
def __init__(self, path, handler):
|
||||
self.slots = threading.BoundedSemaphore(8)
|
||||
super().__init__(path, handler)
|
||||
|
||||
def process_request(self, request, address):
|
||||
if not self.slots.acquire(blocking=False):
|
||||
self.shutdown_request(request)
|
||||
return
|
||||
try:
|
||||
super().process_request(request, address)
|
||||
except BaseException:
|
||||
self.slots.release()
|
||||
raise
|
||||
|
||||
def process_request_thread(self, request, address):
|
||||
try:
|
||||
super().process_request_thread(request, address)
|
||||
finally:
|
||||
self.slots.release()
|
||||
|
||||
def verify_request(self, request, address):
|
||||
if self.vesc_uid == -1:
|
||||
with contextlib.suppress(KeyError):
|
||||
self.vesc_uid = pwd.getpwnam("mission-core-vesc").pw_uid
|
||||
_, uid, _ = struct.unpack(
|
||||
"3i", request.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)
|
||||
)
|
||||
return uid in (0, self.node_uid, self.vesc_uid)
|
||||
|
||||
|
||||
def main():
|
||||
if os.geteuid() == 0:
|
||||
raise RuntimeError("USB-CAN must run unprivileged")
|
||||
service = Service()
|
||||
stop = threading.Event()
|
||||
maintenance = Maintenance()
|
||||
|
||||
def scan():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
with maintenance.work(background=True) as admitted:
|
||||
if admitted: service.scan()
|
||||
except Exception:
|
||||
# A transient discovery failure never kills subsequent hotplug.
|
||||
import logging
|
||||
|
||||
logging.exception("USB-CAN discovery failed")
|
||||
stop.wait(2)
|
||||
|
||||
path = Path("/run/mission-core-usb-can/driver.sock")
|
||||
path.unlink(missing_ok=True)
|
||||
with Server(str(path), Handler) as server:
|
||||
server.node_uid = pwd.getpwnam("mission-core-node").pw_uid
|
||||
try:
|
||||
server.vesc_uid = pwd.getpwnam("mission-core-vesc").pw_uid
|
||||
except KeyError:
|
||||
server.vesc_uid = -1
|
||||
server.service = service
|
||||
server.maintenance = maintenance
|
||||
server.idle = lambda: None if service.prepare_safe() else "can-channel-active"
|
||||
server.quiesce = lambda: None
|
||||
threading.Thread(target=scan, daemon=True, name="usb-can-discovery").start()
|
||||
try:
|
||||
server.serve_forever()
|
||||
finally:
|
||||
stop.set()
|
||||
for device in list(service.devices.values()):
|
||||
device.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,389 @@
|
||||
"""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}
|
||||
@@ -0,0 +1,266 @@
|
||||
"""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()
|
||||
Reference in New Issue
Block a user