Files
NODEDC_MISSION_CORE/plugins/vesc/runtime/service.py
T
DCCONSTRUCTIONS f32c7b400b feat(vesc): extend motor diagnostics, configuration and transport recovery
Add firmware and extension catalogues, configuration transactions, sample review and QML diagnostics. Preserve explicit authority, bounded retries and stop recovery in motor transport.
2026-10-29 09:09:59 +03:00

573 lines
39 KiB
Python

"""One onboard owner; both operator surfaces consume the same bounded device operations."""
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import tempfile
import threading
import time
import uuid
from datetime import datetime, timezone
from . import MODEL, SCHEMA, VERSION
from .protocol import firmware, values, ppm, TEST_LIMITS, SPEED_LIMITS
from .motor_test import MotorTest, Rejected
from .drive_profile import DriveProfile, slot_label, validate as validate_drive
from .control_transport import ControlTransport, validate_routes
from .transport_hub import TransportHub, Missing
from .can_bridge import Attachment as CanAttachment
from .serial import device_id, discover
from .native_link import NativeLink, reap_retired
from .diagnostics import failure, connection
from .read_cache import ReadCache, SNAPSHOT_ACTIONS, EXPIRED
from .bms_configuration import BmsConfiguration, ACTIONS as BMS_CONFIG_ACTIONS, READS as BMS_CONFIG_READS, validate as validate_bms_config
from .package_tools import PackageTools, ACTIONS as PACKAGE_ACTIONS, READS as PACKAGE_READS, validate as validate_packages
from .sample_data import SampleData, ACTIONS as SAMPLE_ACTIONS, validate as validate_samples
from .qml_preview import QmlPreview, ACTIONS as QML_ACTIONS, validate as validate_qml
from .code_tools import CodeTools, ACTIONS as CODE_ACTIONS, READS as CODE_READS, validate as validate_code
from .bms import BmsControl, ACTIONS as BMS_ACTIONS, validate as validate_bms
from .firmware_update import FirmwareUpdate, ACTIONS as FIRMWARE_ACTIONS, SNAPSHOTS as FIRMWARE_SNAPSHOTS, validate as validate_firmware
try:
from .archive import Archive
except ImportError: # Source checkout; packaging copies this exact shared file.
from k1link.device_plugins.vesc.archive import Archive
ACTIONS = frozenset({"verify", "details", "vesc.link.check", "vesc.telemetry.read", "vesc.limits.read", "vesc.configuration.read", "vesc.configuration.preview", "vesc.configuration.apply", "vesc.configuration.reconcile", "vesc.diagnostics.read", "vesc.config.backup", "vesc.input.read", "vesc.can.read", "vesc.transport.configure", "vesc.drive.assign", "vesc.drive.unassign", "vesc.drive.layout", "vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.motor.stop", "vesc.control.release"})
ACTIONS = ACTIONS | SAMPLE_ACTIONS | QML_ACTIONS | PACKAGE_ACTIONS | BMS_CONFIG_ACTIONS | CODE_ACTIONS | BMS_ACTIONS | FIRMWARE_ACTIONS | {"vesc.tools.read", "vesc.terminal.read"}
READ_ACTIONS = frozenset({"verify", "details", "vesc.link.check", "vesc.telemetry.read",
"vesc.limits.read", "vesc.tools.read", "vesc.terminal.read", "vesc.configuration.read", "vesc.diagnostics.read",
"vesc.config.backup", "vesc.configuration.preview", "vesc.configuration.reconcile", "vesc.input.read", "vesc.can.read"})
SNAPSHOT_ACTIONS = SNAPSHOT_ACTIONS | FIRMWARE_SNAPSHOTS
READ_ACTIONS = READ_ACTIONS | SAMPLE_ACTIONS | QML_ACTIONS | PACKAGE_READS | BMS_CONFIG_READS | CODE_READS | {"vesc.bms.read", "vesc.bms.prepare"}
SNAPSHOT_ACTIONS = SNAPSHOT_ACTIONS | SAMPLE_ACTIONS | QML_ACTIONS | PACKAGE_READS | BMS_CONFIG_READS | CODE_READS | {"vesc.bms.read", "vesc.bms.prepare"}
READ_ACTIONS = READ_ACTIONS | (FIRMWARE_ACTIONS - {'vesc.firmware.apply','vesc.firmware.cancel','vesc.firmware.status'})
def utc():
return datetime.now(timezone.utc).isoformat()
def atomic(path, value):
fd, name = tempfile.mkstemp(prefix=".vesc-", dir=path.parent)
try:
with os.fdopen(fd, "w") as stream:
os.fchmod(stream.fileno(), 0o600)
json.dump(value, stream, ensure_ascii=False, allow_nan=False)
stream.flush()
os.fsync(stream.fileno())
os.replace(name, path)
fd = os.open(path.parent, os.O_RDONLY)
try:
os.fsync(fd)
finally:
os.close(fd)
finally:
if os.path.exists(name):
os.unlink(name)
class Device:
def __init__(self, attachment):
self.attachment = attachment
self.id = attachment.id
self.session = "vesc_" + uuid.uuid4().hex
self.opened = utc()
self.link = None
self.identity = None
self.error = None
self.telemetry = None
self.backup = None
self.lock = threading.Lock()
self.retry_at = 0
self.failure_at = 0
self.failures = 0
self.sample = None
self.identified_session = None
@property
def readable(self):
identity = self.identity
return self.readable_identity(identity) and getattr(self.link,"engine",{}).get("firmware_admitted",True)
@staticmethod
def readable_identity(identity):
return bool(identity and identity["major"] in (5, 6, 7)
and identity["hardware_type"] in (None, 0))
def connect(self, factory):
with self.lock:
try:
self.session = "vesc_" + uuid.uuid4().hex
self.opened = utc()
self.identified_session = None
self.sample = self.telemetry = None
self.link = factory(self.attachment)
identity = firmware(self.link.query(0))
if isinstance(self.attachment, CanAttachment) and identity["uuid"] != self.attachment.expected_uuid:
raise ValueError("На этом CAN-адресе другой UUID VESC.")
self.identity = identity
self.id = device_id("uuid:" + identity["uuid"])
self.identified_session = self.session
self.error = None
connection("identified", self)
# A firmware reply alone does not reset repeated read failures.
except Exception as error:
self.failed(error, "connection")
def failed(self, error, phase):
"""Called with device.lock held. One retry deadline, no retry worker."""
previous_session = self.session
if self.link is not None or self.sample is not None:
connection("read_failed", self, error)
link, self.link = self.link, None
self.sample = self.telemetry = None
self.session = "vesc_" + uuid.uuid4().hex
self.failures = min(self.failures + 1, 5)
self.retry_at = time.monotonic() + min(2 ** self.failures, 30)
self.error = "Нет ответа VESC. Повторное подключение выполняется автоматически."
try:
if link: link.close()
except Exception as cleanup_error:
if time.monotonic() >= self.failure_at:
failure(cleanup_error, "connection-cleanup", device=self)
if time.monotonic() >= self.failure_at:
self.failure_at = time.monotonic() + 30
failure(error, phase, device=self, session_id=previous_session)
def publish_sample(self, value, receiver):
restored = self.sample is None
self.sample = {"session_id": self.session, "values": value,
"receiver": receiver, "sampled_at": time.monotonic(), "observed_at": utc()}
self.failures = 0
self.retry_at = 0
self.error = None
if restored:
connection("sample_restored", self)
def close(self):
with self.lock:
connection("usb_detached", self)
link, self.link = self.link, None
self.sample = self.telemetry = None
self.session = "vesc_" + uuid.uuid4().hex
try:
if link: link.close()
except Exception as error:
if time.monotonic() >= self.failure_at:
self.failure_at = time.monotonic() + 30
failure(error, "connection-close", device=self)
class Service:
def __init__(self, root, discover_fn=discover, link_factory=NativeLink):
self.root = Path(root)
self.root.mkdir(mode=0o700, parents=True, exist_ok=True)
self.archive = Archive(self.root / "archive")
for path in sorted(self.root.glob("backup_op_*.json")):
self.archive.add("local", json.loads(path.read_text()))
self.discover_fn, self.link_factory = discover_fn, link_factory
self.devices = {}
self.lock = threading.RLock()
self.operation_lock = threading.Lock()
self.journal_lock = threading.Lock()
self.read_cache = ReadCache()
self.motor = MotorTest(self, atomic, utc)
from .config_editor import ConfigEditor
self.config_editor = ConfigEditor(self, atomic, utc)
self.firmware_update = FirmwareUpdate(self, atomic, utc)
self.bms = BmsControl(self, atomic, utc)
self.bms_configuration = BmsConfiguration(self, atomic, utc)
self.code_tools = CodeTools(self, atomic, utc)
self.samples = SampleData(self)
self.qml = QmlPreview(self)
self.qml_utc = utc
self.packages = PackageTools(self, atomic, utc)
self.drive = DriveProfile(self.root, atomic)
self.instance = "vesc_" + uuid.uuid4().hex
self.revision = 0
self.device_type = Device
self.transport = ControlTransport(self.root, atomic)
self.transports = TransportHub(self, atomic)
def scan(self):
reap_retired()
self.transports.scan()
with self.lock: devices = list(self.devices.values())
if self.operation_lock.acquire(blocking=False):
try:
self.qml.maintain(devices)
self.samples.maintain(devices)
for device in devices:
if device.link is not None and not self.firmware_update.pending(device) and not self.bms_configuration.pending(device) and not self.code_tools.blocked(device) and self.motor.limits.pending(device):
with device.lock:
try:
self.motor.limits.restore(device)
device.error = None
except (OSError, ValueError, TimeoutError):
device.error = "Прежние токовые пределы ещё не восстановлены. Новые проверки заблокированы."
finally:
self.operation_lock.release()
with self.lock:
self.revision += 1
def inventory(self, node_id):
with self.lock:
# Copy each generation before counting identities. Serial I/O never
# holds the inventory lock; it can complete during this projection.
devices = [d.__dict__.copy() for d in self.devices.values()]
keys = [device_id("uuid:" + d["identity"]["uuid"]) if d["identity"] else d["attachment"].id for d in devices]
items = []
for d, key in zip(devices, keys):
identity, attachment = d["identity"], d["attachment"]
unique = keys.count(key) == 1 and identity is not None
available = (unique and d["identified_session"] == d["session"]
and d["link"] is not None and getattr(d["link"], "alive", True))
sample = d["sample"] if available and d["sample"] and d["sample"]["session_id"] == d["session"] else None
identifier = key if unique else attachment.id
message = d["error"] if keys.count(key) == 1 else "Контроллеры сообщили одинаковый UUID. Настройка недоступна."
items.append({"id": identifier, "attachment_id": attachment.id,
"name": "VESC " + (identity["uuid"][:6].upper() if unique else "· USB " + attachment.usb),
"model": identity["hardware"] if unique else "VESC · USB", "kind": MODEL,
"firmware": identity["version"] if unique else None,
"initializable": True, "prepared": True, "configured": unique, "verified": bool(available),
"preparation_safe": True, "online": bool(available) if isinstance(attachment, CanAttachment) else not isinstance(attachment, Missing), "usb": attachment.speed,
"connection_label": (attachment.usb if isinstance(attachment, CanAttachment) else "Недоступно" if isinstance(attachment, Missing) else "USB " + attachment.usb) + next((" · " + slot_label(self.drive.value["layout"], slot) for slot, binding in self.drive.value["bindings"].items() if binding["device_id"] == identifier), ""), "layers": [],
"vesc_status": {"identity": identity if unique else None, "readable": bool(available) and Device.readable_identity(identity) and getattr(d["link"],"engine",{}).get("firmware_admitted",True),
"connected": bool(available), "telemetry_ready": sample is not None,
"engine": getattr(d["link"], "engine", None), "message": message, "telemetry": d["telemetry"] if available else None, "backup": d["backup"], "configuration_read_supported": True, "configuration_edit_supported": True, "firmware_update_supported": True, "tools_read_supported": True, "terminal_read_supported": True, "firmware_update": self.firmware_update.status(identifier), "configuration_pending": self.config_editor.pending_path(identifier).exists(), "bms_configuration_pending": self.bms_configuration.path(identifier).exists(), "package_pending": self.packages.path(identifier).exists(), "code_pending": self.code_tools.path(identifier).exists(), "code_execution_pending": self.code_tools.path(identifier,"execution").exists(), "diagnostics_read_supported": True, "qml_preview_supported": True, "qml_interactive_supported": True, "qml_broker_supported": "qml_read" in (getattr(d["link"], "engine", None) or {}).get("contract", {}).get("methods", []), "sample_data_supported": bool(identity and identity["version"] == "5.02"), "board_settings_supported": True, "group_test_supported": True, "link_check_supported": True, "test_supported": bool(available) and identity["version"] == "5.02" and identity["hardware"] == "75_300_R2", "control_transport": self.transports.profile(), "control_endpoints": self.transports.endpoints(), "control_adapters": [{**a, "label": a["name"]} for a in self.transports.adapters], "drive_profile": self.drive.value, "test_limits": TEST_LIMITS, "speed_limits": SPEED_LIMITS, "hall_measurement": {"current_a": 5, "interruptible": False, "standstill_confirmation_required": True}, "foc_calibration": {"min_power_loss_w": 10, "max_power_loss_w": 150, "interruptible": False}, "test_mode": self.motor.mode, "test_active": self.motor.active, "rc_latched": self.motor.latched},
"snapshot": {"context": {"session_id": d["session"],
"device": {"device_id": identifier, "model": {"plugin_id": "missioncore.vesc",
"plugin_version": VERSION, "model_id": MODEL},
"stability": "stable" if unique else "provisional",
"basis": "hardware-identifier" if unique else "transport-local"},
"execution": {"node_id": node_id, "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 validate(self, command):
if not isinstance(command, dict) or command.get("api_version") != SCHEMA or command.get("kind") != "OperationRequest":
raise ValueError("Invalid contract")
identifier = command.get("operation_id", "")
if not re.fullmatch(r"op_[0-9a-f]{32}", identifier) or command.get("idempotency_key") != identifier:
raise ValueError("Invalid operation identity")
action, params = command.get("action_id"), command.get("parameters")
if action not in ACTIONS or not isinstance(params, dict):
raise ValueError("Unsupported operation")
if action in ("vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.control.release"):
keys = {"sessions", "rig_clear", "duration_s", "current_a"} | ({"standstill_confirmed"} if action != "vesc.motor.pulse" else set()) | ({"erpm"} if action in ("vesc.motor.run", "vesc.drive.run") else set()) | ({"profile_revision", "device_ids"} if action == "vesc.drive.run" else set())
if (set(params) != keys or params["rig_clear"] is not True
or not isinstance(params["sessions"], dict) or not 1 <= len(params["sessions"]) <= 128
or type(params["current_a"]) not in (int, float) or not TEST_LIMITS["min_current_a"] <= params["current_a"] <= TEST_LIMITS["max_current_a"]
or type(params["duration_s"]) not in (int, float) or not TEST_LIMITS["min_duration_s"] <= params["duration_s"] <= TEST_LIMITS["max_duration_s"]):
raise ValueError("Explicit raised-rig confirmation, duration and controller sessions required")
if action != "vesc.motor.pulse" and params["standstill_confirmed"] is not True:
raise ValueError("Explicit observation of all motors at standstill required")
if action in ("vesc.motor.run", "vesc.drive.run") and (type(params["erpm"]) not in (int, float) or not SPEED_LIMITS["min_erpm"] <= abs(params["erpm"]) <= SPEED_LIMITS["max_erpm"]):
raise ValueError("Speed is outside the supported range")
if action == "vesc.drive.run" and (type(params["profile_revision"]) is not int or params["profile_revision"] < 0
or not isinstance(params["device_ids"], list) or not 2 <= len(params["device_ids"]) <= 128
or any(not isinstance(v, str) for v in params["device_ids"])
or len(set(params["device_ids"])) != len(params["device_ids"])):
raise ValueError("Explicit complete drive profile required")
elif action in ("vesc.hall.measure", "vesc.foc.calibrate"):
extra = {"max_power_loss_w"} if action == "vesc.foc.calibrate" else {"standstill_confirmed"}
if (set(params) != ({"sessions", "rig_clear", "native_cycle_confirmed"} | extra)
or params["rig_clear"] is not True or params["native_cycle_confirmed"] is not True
or not isinstance(params["sessions"], dict) or not 1 <= len(params["sessions"]) <= 128):
raise ValueError("Native procedure and rig confirmation required")
if action == "vesc.hall.measure" and params["standstill_confirmed"] is not True:
raise ValueError("Explicit observation of all motors at standstill required")
if action == "vesc.foc.calibrate" and (type(params["max_power_loss_w"]) not in (int,float) or not 10 <= params["max_power_loss_w"] <= 150):
raise ValueError("Heating budget must be between 10 and 150 W")
elif action == "vesc.tools.read":
if set(params) != {'tool'} or params['tool'] not in ('adc','chuk','imu','bms'):
raise ValueError('Unknown peripheral tool')
elif action == "vesc.terminal.read":
if set(params) != {'command'} or params['command'] not in ("hw_status", "faults", "fault", "ping", "mem", "threads", "rpm", "tacho", "volt", "uptime", "help"):
raise ValueError('Only admitted read-only terminal commands are supported')
elif action in BMS_CONFIG_ACTIONS:
validate_bms_config(action, params)
elif action in PACKAGE_ACTIONS:
validate_packages(action, params)
elif action in SAMPLE_ACTIONS:
validate_samples(action, params)
elif action in QML_ACTIONS:
validate_qml(action, params)
elif action in CODE_ACTIONS:
validate_code(action, params)
elif action in BMS_ACTIONS:
validate_bms(action, params)
elif action in FIRMWARE_ACTIONS:
validate_firmware(action, params)
elif action.startswith("vesc.configuration.") and action != "vesc.configuration.read":
from .config_editor import validate
validate(action, params)
elif action == "vesc.link.check":
if set(params) != {"sessions"} or not isinstance(params["sessions"], dict) or not 1 <= len(params["sessions"]) <= 128:
raise ValueError("Controller sessions required")
elif action == "vesc.transport.configure":
if not isinstance(params, dict) or set(params) != {"revision", "drive_revision", "routes"}:
raise ValueError("Invalid control transport profile")
validate_routes(params["routes"], self.drive.value)
elif action in ("vesc.drive.assign", "vesc.drive.unassign", "vesc.drive.layout"):
validate_drive(action, params)
elif params != {}:
raise ValueError("This operation has no parameters")
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:
raise ValueError("Invalid operation deadline")
return end
def execute(self, command):
deadline = self.validate(command)
path = self.root / (command["operation_id"] + ".json")
digest = hashlib.sha256(json.dumps(command, sort_keys=True).encode()).hexdigest()
if command["action_id"] in ("vesc.firmware.status", "vesc.firmware.cancel"):
# Status/cancel are RAM/file operations and remain available while
# the uploading request holds the exclusive hardware lock.
with self.journal_lock:
if path.exists():
previous = json.loads(path.read_text())
if previous['digest'] != digest: raise ValueError('Operation identity conflict')
return self.read_cache.get(command['operation_id']) if previous.get('snapshot_only') else previous['receipt']
if deadline <= datetime.now(timezone.utc): raise ValueError('Operation expired')
identifier = command['session']['device_id']
with self.lock:
if not any(d.id == identifier for d in self.devices.values()):
raise ValueError('Device no longer present')
result = (self.firmware_update.status(identifier) if command['action_id'].endswith('.status')
else self.firmware_update.cancel(identifier, command['parameters']['operation_id']))
receipt = {'state':'complete','result':result}
if command['action_id'].endswith('.status'):
if sum(p.stat().st_size for p in self.root.glob('*.json')) > 32 * 1024 * 1024:
raise ValueError('Read journal is full')
self.read_cache.put(command['operation_id'], receipt)
atomic(path, {'digest':digest,'snapshot_only':True,'receipt':EXPIRED})
else: atomic(path, {'digest':digest,'receipt':receipt})
return receipt
if command["action_id"] == "vesc.motor.stop":
with self.journal_lock:
if path.exists():
previous = json.loads(path.read_text())
if previous["digest"] != digest: raise ValueError("Operation identity conflict")
return previous["receipt"]
if deadline <= datetime.now(timezone.utc): raise ValueError("Operation expired")
self.motor.cancel()
result = {"state": "complete", "result": {"stop_requested": True, "interruptible": self.motor.mode not in ("hall", "foc"), "drive_profile": self.drive.value, "test_limits": TEST_LIMITS, "test_active": self.motor.active}}
atomic(path, {"digest": digest, "receipt": result})
return result
# Observer samples own the same lock for a short exchange. Read requests
# wait at most half a second, within their remaining read budget.
# Powered operations keep immediate admission; no delayed motor start.
wait = max(0.0, min(.5, (deadline-datetime.now(timezone.utc)).total_seconds()-8)) if command["action_id"] in READ_ACTIONS or command["action_id"] == "vesc.transport.configure" else 0.0
if not self.operation_lock.acquire(timeout=wait):
raise ValueError("Another VESC operation is running")
try:
if path.exists():
previous = json.loads(path.read_text())
if previous["digest"] != digest:
raise ValueError("Operation identity conflict")
if command["action_id"] in SNAPSHOT_ACTIONS and previous.get("snapshot_only"):
return self.read_cache.get(command["operation_id"])
return previous["receipt"]
if deadline <= datetime.now(timezone.utc):
raise ValueError("Operation expired")
with self.lock:
matches = [d for d in self.devices.values() if d.id == command["session"]["device_id"]]
if len(matches) != 1 or matches[0].session != command["session"]["session_id"]:
raise ValueError("Device session changed")
device = matches[0]
# Keep backups and receipts bounded without deleting evidence automatically.
if sum(p.stat().st_size for p in self.root.glob("*.json")) > 32 * 1024 * 1024:
raise ValueError("Read journal is full")
record = {"digest": digest, "receipt": {"state": "unknown", "error": "Чтение не подтверждено. Обновите состояние."}}
with self.journal_lock:
if path.exists(): raise ValueError("Operation identity already reserved")
atomic(path, record)
try:
if self.samples.active(device) and command["action_id"] in {
"vesc.firmware.apply", "vesc.firmware.target", "vesc.firmware.backup", "vesc.configuration.apply",
"vesc.bms.configuration.apply", "vesc.bms.configuration.read", "vesc.bms.configuration.preview",
"vesc.bms.read", "vesc.bms.apply", "vesc.code.apply", "vesc.code.control_apply",
"vesc.packages.apply", "vesc.hall.measure", "vesc.foc.calibrate"}:
raise Rejected("Сначала остановите Sample Data или дождитесь окончания захвата.")
if command["action_id"] == "vesc.link.check":
from .link_check import measure
with self.lock: devices = list(self.devices.values())
result = measure(self, command, devices)
record["receipt"] = {"state": "complete", "result": result}
atomic(path, record)
return record["receipt"]
if command["action_id"] == "vesc.transport.configure":
try:
result = self.transport.update(command["parameters"], self.drive.value, active=self.motor.active or (getattr(self, "remote", None) is not None and self.remote.state == "preparing"))
self.transports.select()
except ValueError as error:
raise Rejected(str(error)) from error
record["receipt"] = {"state": "complete", "result": {"control_transport": result}}
atomic(path, record)
return record["receipt"]
if command["action_id"] in ("vesc.drive.assign", "vesc.drive.unassign", "vesc.drive.layout"):
if device.identity is None: raise Rejected("Сначала подтвердите личность VESC.")
try:
result = self.drive.update(command["action_id"], command["parameters"], device)
except ValueError as error:
raise Rejected(str(error)) from error
record["receipt"] = {"state": "complete", "result": result}
atomic(path, record)
return record["receipt"]
if command["action_id"] in ("vesc.motor.pulse", "vesc.motor.run", "vesc.drive.run", "vesc.hall.measure", "vesc.foc.calibrate", "vesc.control.release"):
with self.lock:
devices = list(self.devices.values())
actual = {d.id: d.session for d in devices}
if len(actual) != len(devices) or actual != command["parameters"]["sessions"]:
raise Rejected("Состав или сеансы VESC изменились. Обновите устройства.")
run_command = command
if command["action_id"] == "vesc.hall.measure":
run_command = {**command, "parameters": {**command["parameters"], "current_a": 5, "duration_s": 30}}
if command["action_id"] == "vesc.foc.calibrate":
run_command = {**command, "parameters": {**command["parameters"], "current_a": 5, "duration_s": 225}}
result = self.motor.run(run_command, devices, device, command["action_id"] == "vesc.control.release")
record["receipt"] = {"state": "complete", "result": result}
atomic(path, record)
return record["receipt"]
with device.lock:
if device.link is None:
raise OSError("Device disconnected")
if command["action_id"] not in READ_ACTIONS | CODE_ACTIONS | BMS_CONFIG_ACTIONS | PACKAGE_ACTIONS and (self.bms_configuration.pending(device) or self.code_tools.blocked(device)):
raise Rejected("Сначала подтвердите изменение BMS/кода и остановите Lisp.")
remaining = (deadline - datetime.now(timezone.utc)).total_seconds()
if remaining < 8:
raise TimeoutError("Insufficient time for bounded read")
# Local QML staging/input never interrogates USB; retain
# the binding to this exact live attachment and session.
if command["action_id"] in QML_ACTIONS:
device.link.check()
actual = device.identity
else:
actual = firmware(device.link.query(0))
if actual != device.identity:
device.link.close()
device.link = None
device.identity = None
device.session = "vesc_" + uuid.uuid4().hex
raise ValueError("Controller identity changed")
result = {"identity": actual, "device_id": device.id, "observed_at": utc()}
action = command["action_id"]
if action in {"vesc.telemetry.read", "vesc.limits.read", "vesc.tools.read", "vesc.terminal.read", "vesc.configuration.read", "vesc.diagnostics.read", "vesc.config.backup"} and not device.readable:
raise ValueError("Firmware read layout is unsupported")
if action == "vesc.telemetry.read":
result.update(values=values(device.link.query(4)), monotonic_at=time.monotonic())
device.telemetry = result
elif action == 'vesc.tools.read':
result.update(device.link.device_tool(command['parameters']['tool']))
if command['parameters']['tool']=='bms':
# FW5.02 proxy omits these fields. Native decoder defaults
# are not measurements or evidence of a connected BMS.
result['source']='controller_cache'
result['source_age_known']=False
if actual['version']=='5.02':
for key in ('can_id','ah_cnt_chg_total','wh_cnt_chg_total','ah_cnt_dis_total','wh_cnt_dis_total','pressure','data_version','status'):
result.get('values',{}).pop(key,None)
elif action == 'vesc.terminal.read':
result.update(device.link.diagnostic(command['parameters']['command']))
elif action in BMS_CONFIG_ACTIONS:
if action.endswith(".apply") and self.code_tools.blocked(device): raise Rejected("Сначала подтвердите запись кода и остановите Lisp.")
result.update(self.bms_configuration.execute(device,action,command["parameters"],command["operation_id"],deadline))
elif action in PACKAGE_ACTIONS:
result.update(self.packages.execute(device,action,command["parameters"],command["operation_id"],deadline))
elif action in SAMPLE_ACTIONS:
result.update(self.samples.execute(device, action, command["parameters"]))
elif action in QML_ACTIONS:
result.update(self.qml.execute(device, action, command["parameters"]))
elif action in CODE_ACTIONS:
result.update(self.code_tools.execute(device,action,command["parameters"],command["operation_id"],deadline))
elif action in BMS_ACTIONS:
if not device.readable:raise Rejected('Бортовой VESC не поддерживает адресный BMS.')
if action=='vesc.bms.read': result.update(self.bms.read(device,command['parameters']['can_id']))
elif action=='vesc.bms.prepare': result.update(self.bms.prepare(device,command['parameters']))
else: result.update(self.bms.apply(device,command['parameters'],command['operation_id']))
elif action in FIRMWARE_ACTIONS:
if action == 'vesc.firmware.apply':
result.update(self.firmware_update.apply(device,command['parameters'],command['operation_id'],deadline))
elif action == 'vesc.firmware.reconcile':
result.update(self.firmware_update.reconcile(device))
else: result.update(self.firmware_update.stage(device,action,command['parameters']))
elif action == "vesc.configuration.read":
result["configuration"] = device.link.configuration()
if firmware(device.link.query(0)) != actual:
raise ValueError("Controller changed during configuration read")
elif action == "vesc.configuration.preview":
result.update(self.config_editor.preview(device, command["parameters"]))
elif action == "vesc.configuration.apply":
result.update(self.config_editor.apply(device, command["parameters"], command["operation_id"], deadline))
elif action == "vesc.configuration.reconcile":
result.update(self.config_editor.reconcile(device))
elif action == "vesc.diagnostics.read":
from .controller_diagnostics import read_diagnostics
result.update(read_diagnostics(device))
if firmware(device.link.query(0)) != actual:
raise ValueError("Controller changed during diagnostic read")
elif action == "vesc.limits.read":
from .limits_view import read_limits
result.update(parameters=read_limits(device.link))
if firmware(device.link.query(0)) != actual:
raise ValueError("Controller changed during configuration read")
elif action == "vesc.input.read":
if actual["version"] != "5.02": raise ValueError("Input layout unsupported")
result["input"] = ppm(device.link.query(31))
elif action == "vesc.can.read":
if actual["version"] != "5.02": raise ValueError("CAN layout unsupported")
started = time.monotonic()
reply = device.link.query(62, timeout=8)
if not reply or reply[0] != 62: raise ValueError("Invalid CAN reply")
result.update(can_ids=list(reply[1:]), elapsed_s=time.monotonic()-started)
elif action == "vesc.config.backup":
configs = {}
for name, code in (("motor", 14), ("application", 17)):
raw = device.link.query(code)
if not 5 <= len(raw) <= 10000:
raise ValueError("Incomplete configuration")
configs[name] = {"encoding": "base64", "payload": base64.b64encode(raw).decode(),
"bytes": len(raw), "sha256": hashlib.sha256(raw).hexdigest(),
"signature_hex": raw[1:5].hex()}
# Identity is checked on the same exclusively held attachment at both ends.
if firmware(device.link.query(0)) != actual:
raise ValueError("Controller changed during backup")
result.update(schema="missioncore.vesc.config-backup/v1", configs=configs,
decoded=False, operation_id=command["operation_id"], monotonic_at=time.monotonic())
backup_path = self.root / ("backup_" + command["operation_id"] + ".json")
atomic(backup_path, result)
self.archive.add("local", result)
device.backup = {"observed_at": result["observed_at"], "operation_id": command["operation_id"],
"configs": {k: {"bytes": v["bytes"], "sha256": v["sha256"]} for k, v in configs.items()}}
record["receipt"] = {"state": "complete", "result": result}
except (OSError, ValueError, TimeoutError) as error:
record["receipt"] = {"state": "error", "error": str(error) if isinstance(error, Rejected) else "Операция не выполнена. Проверьте связь и совместимость контроллера."}
if getattr(error, "native_rpc", None) is not None:
# Keep transport evidence in the receipt, not product copy.
# This covers ordinary reads and preflight before a motor
# procedure has its own result/failure envelope.
record["receipt"]["result"] = {"failure": {
"type": type(error).__name__, "native_rpc": error.native_rpc,
"native_history": getattr(error, "native_history", []),
}}
if command["action_id"] in SNAPSHOT_ACTIONS:
self.read_cache.put(command["operation_id"], record["receipt"])
atomic(path, {"digest": digest, "snapshot_only": True, "receipt": EXPIRED})
else:
atomic(path, record)
return record["receipt"]
finally:
self.operation_lock.release()