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.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:09:59 +03:00
parent 115476d2e6
commit f32c7b400b
186 changed files with 21197 additions and 339 deletions
+266 -58
View File
@@ -16,16 +16,39 @@ 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
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.config.backup", "vesc.input.read", "vesc.can.read", "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 = 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()
@@ -62,11 +85,15 @@ class Device:
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)
return self.readable_identity(identity) and getattr(self.link,"engine",{}).get("firmware_admitted",True)
@staticmethod
def readable_identity(identity):
@@ -77,23 +104,64 @@ class Device:
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
except (OSError, ValueError, TimeoutError):
if self.link:
self.link.close()
self.link = None
self.error = "Контроллер не ответил. Проверьте питание, USB и доступность порта."
self.retry_at = time.monotonic() + 15
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:
if self.link:
self.link.close()
self.link = None
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:
@@ -108,31 +176,35 @@ class Service:
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):
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 device in removed:
device.close()
for device in devices:
if device.link is not None and not getattr(device.link, "alive", True):
device.close()
if device.link is None and time.monotonic() >= device.retry_at:
device.connect(self.link_factory)
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 self.motor.limits.pending(device):
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)
@@ -149,32 +221,36 @@ class Service:
# 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"] and d["link"] 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 and d["link"] is not 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": unique,
"preparation_safe": True, "online": True, "usb": attachment.speed,
"connection_label": "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": unique and Device.readable_identity(identity),
"engine": getattr(d["link"], "engine", None), "message": message, "telemetry": d["telemetry"], "backup": d["backup"], "board_settings_supported": True, "group_test_supported": True, "link_check_supported": True, "test_supported": unique and identity["version"] == "5.02" and identity["hardware"] == "75_300_R2", "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 unique else "degraded", "message": message}})
return {"items": items}
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":
@@ -211,9 +287,36 @@ class Service:
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 != {}:
@@ -228,6 +331,29 @@ class Service:
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():
@@ -239,13 +365,19 @@ class Service:
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
if not self.operation_lock.acquire(blocking=False):
# 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")
@@ -262,6 +394,12 @@ class Service:
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())
@@ -269,6 +407,15 @@ class Service:
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:
@@ -296,10 +443,18 @@ class Service:
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")
actual = firmware(device.link.query(0))
# 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
@@ -308,11 +463,60 @@ class Service:
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.config.backup"} and not device.readable:
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))
@@ -357,7 +561,11 @@ class Service:
"type": type(error).__name__, "native_rpc": error.native_rpc,
"native_history": getattr(error, "native_history", []),
}}
atomic(path, record)
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: