"""Private lifecycle/RPC boundary to unmodified upstream VESC Tool C++. No wire encoding or calibration algorithm lives here. The native process owns one exact USB attachment and sends all commands through upstream Commands. """ import base64 from collections import deque import hashlib import json import os from pathlib import Path import select import subprocess import time import threading from .serial import check_attachment # A process stuck in kernel USB I/O may outlive SIGKILL. Keep its ownership # until poll confirms exit; do not accumulate replacement owners or waiter threads. _retiring = {} _retiring_lock = threading.Lock() def reap_retired(tty=None): with _retiring_lock: for key, process in list(_retiring.items()): if process.poll() is not None: del _retiring[key] if tty in _retiring: raise OSError("Previous native USB owner has not exited") class NativeLink: def __init__(self, attachment): self.attachment = attachment self.process = None self.bridge = None self.buffer = b"" self.sequence = 0 self.hall_pending = False self.history = deque(maxlen=32) reap_retired(attachment.tty) from .can_bridge import Attachment, Bridge if isinstance(attachment, Attachment): self.bridge = Bridge(attachment) self.check() root = Path("/usr/lib/mission-core-vesc/native") config = Path("/run/mission-core-vesc/native") / hashlib.sha256(attachment.binding.encode()).hexdigest()[:24] config.mkdir(parents=True, mode=0o700, exist_ok=True) env = dict(os.environ, QT_QPA_PLATFORM="offscreen", XDG_CONFIG_HOME=str(config), XDG_CACHE_HOME=str(config / "cache"), LD_LIBRARY_PATH=str(root / "lib"), QT_PLUGIN_PATH=str(root / "plugins"), TMPDIR=str(config)) target = "--can-bridge=" + str(self.bridge.port) if self.bridge else "/dev/" + attachment.tty # Preserve native startup diagnostics in the private runtime directory. try: with (config / "engine.log").open("wb") as diagnostic: self.process = subprocess.Popen([str(root / "bin/mission-core-vesc-engine"), target], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=diagnostic, env=env, bufsize=0, close_fds=True) except BaseException: if self.bridge: self.bridge.close() raise try: hello = self._receive(time.monotonic() + 6) if hello.get("ready") is not True or not hello.get("engine", {}).get("connected"): raise OSError("Native VESC Tool did not connect") self.engine = hello["engine"] manifest = json.loads((root / "manifest.json").read_bytes()) if (self.engine.get("contract", {}).get("rpc_version") != 1 or self.engine.get("contract") != manifest.get("engine_contract") or self.engine.get("version") != manifest.get("upstream_version") or self.engine.get("commit") != manifest.get("upstream_commit")): raise OSError("Native engine contract does not match the installed release") self.check() except BaseException as error: # Preserve this attempt's evidence before close/retry replaces it. try: with (config / "engine.log").open("rb") as diagnostic: diagnostic.seek(0, os.SEEK_END) size = diagnostic.tell() diagnostic.seek(max(0, size - 4096)) tail = diagnostic.read(4096).decode("utf-8", errors="replace") error.native_startup = {"pid": self.process.pid, "exit_code": self.process.poll(), "stderr_tail": tail, "stderr_truncated": size > 4096} except Exception: pass if self.bridge: error.can_bridge = self.bridge.diagnostics() self.close() raise @property def alive(self): return (self.process is not None and self.process.poll() is None and not (getattr(self, "bridge", None) and self.bridge.stop.is_set())) def check(self): if getattr(self, "bridge", None): self.bridge.check() else: check_attachment(self.attachment) def failure_error(self): bridge = getattr(self, "bridge", None) if bridge and bridge.error: return OSError("CAN bridge: " + str(bridge.error)[:512]) code = self.process.poll() if self.process is not None else None return OSError(f"Native transport exited (code={code})") def _receive(self, deadline): while b"\n" not in self.buffer: if not self.alive: raise self.failure_error() if not select.select([self.process.stdout], [], [], max(0, deadline-time.monotonic()))[0]: if not self.alive: raise self.failure_error() raise TimeoutError("Native VESC Tool response timed out") data = os.read(self.process.stdout.fileno(), 65536) if not data: raise self.failure_error() self.buffer += data if len(self.buffer) > 2 * 1024 * 1024: raise ValueError("Native response exceeds bound") line, self.buffer = self.buffer.split(b"\n", 1) return json.loads(line) def rpc(self, method, timeout=2, **parameters): # These two methods only inspect/cancel the already-owned native job. # They must survive the expected USB detach caused by fwUpload itself; # no other method may bypass exact-attachment validation. detached_status = method in ('firmware_status','firmware_cancel') self.sequence += 1 request = json.dumps({"id": self.sequence, "method": method, **parameters}, allow_nan=False).encode()+b"\n" if len(request) > (2*1024*1024 if method == "package_unpack" else 512*1024 if method in ("code_pack", "code_write") else 65536): raise ValueError("Native request exceeds bound") started = time.monotonic() deadline = started + timeout trace = {"method": method, "command": parameters.get("command"), "timeout_ms": parameters.get("timeout_ms", timeout*1000), "attachment": {"usb": self.attachment.usb, "address": self.attachment.address, "tty": self.attachment.tty}} try: trace["stage"] = "attachment_before" if not detached_status: self.check() trace["attachment_before_ms"] = (time.monotonic()-started)*1000 trace["stage"] = "request_write" if not self.alive: raise OSError("Native VESC Tool is not running") if not select.select([], [self.process.stdin], [], max(0, deadline-time.monotonic()))[1]: raise TimeoutError("Native VESC Tool request timed out") offset = 0 while offset < len(request): if not select.select([], [self.process.stdin], [], max(0, deadline-time.monotonic()))[1]: raise TimeoutError("Native request write timed out") written = os.write(self.process.stdin.fileno(), request[offset:offset+4096]) if written <= 0: raise OSError("Native request write incomplete") offset += written sent_at = time.monotonic() trace["request_write_ms"] = (sent_at-started)*1000-trace["attachment_before_ms"] trace["stage"] = "native_response" response = self._receive(deadline) received_at = time.monotonic() trace["native_response_ms"] = (received_at-sent_at)*1000 if not isinstance(response, dict): raise ValueError("Invalid native response") if response.get("id") != self.sequence: raise ValueError("Native response identity mismatch") if isinstance(response.get("control"), dict): trace["control"] = response["control"] if getattr(self, "bridge", None): trace["can_bridge"] = self.bridge.diagnostics() if response.get("ok") is not True: if isinstance(response.get("diagnostics"), dict): trace["transport"] = response["diagnostics"] raise OSError(response.get("error", "Native operation failed")) trace["stage"] = "attachment_after" if not detached_status: self.check() trace["attachment_after_ms"] = (time.monotonic()-received_at)*1000 trace["stage"] = "complete" result = response.get("result") if not isinstance(result, dict): raise ValueError("Invalid native result") trace.update(ok=True, elapsed_ms=(time.monotonic()-started)*1000) self.last_rpc = trace if hasattr(self, "history"): self.history.append(trace) return result except (OSError, ValueError, TimeoutError) as error: # An unconfirmed reply is never silently retried on the same stream. trace.update(ok=False, elapsed_ms=(time.monotonic()-started)*1000, process_alive=self.alive, error=str(error)) try: self.check(); trace["attachment_present"] = True except OSError: trace["attachment_present"] = False if getattr(self, "bridge", None): trace["can_bridge"] = self.bridge.diagnostics() self.last_rpc = trace if hasattr(self, "history"): self.history.append(trace) error.native_rpc = trace error.native_history = list(getattr(self, "history", [])) trace["cleanup"] = self.close() raise def query(self, command, timeout=2): result = self.rpc("query", timeout=timeout+0.1, command=command, timeout_ms=max(20, int(timeout*1000))) return base64.b64decode(result["payload"], validate=True) def test_command(self, action): if action not in ("claim", "release"): raise ValueError("Unknown control action") self.rpc("lease" if action == "claim" else "release", timeout=0.1) def test_current(self, current_a): self.rpc("current", timeout=0.1, current_a=current_a) def test_speed(self, erpm): self.rpc("rpm", timeout=0.1, erpm=erpm) def drive_duty(self, duty, current_a): self.rpc("duty_limited", timeout=0.1, duty=duty, current_a=current_a) def set_temporary_limits(self, config): from .temporary_limits import FIELDS self.rpc("limits", timeout=2.2, parameters={k: config[k] for k in FIELDS}) def diagnostic(self, command): return self.rpc("diagnostic", timeout=3.5, command=command) def device_tool(self, tool): return self.rpc("device_tool",timeout=3,tool=tool) def bms_read(self, can_id): return self.rpc("bms_read", timeout=6, can_id=can_id) def bms_command(self, target, command): return self.rpc("bms_command", timeout=3, can_id=target['can_id'], target=target, command=command) def configuration(self): return self.rpc("configuration", timeout=5) def configuration_preview(self, sources): return self.rpc("configuration_preview", timeout=6, sources=sources) def configuration_apply(self, kind, target): return self.rpc("configuration_apply", timeout=9, kind=kind, **{k: target[k] for k in ("payload", "before_sha256", "after_sha256")}) def firmware_rpc(self, action, **parameters): if action not in ('begin','chunk','seal','start','status','cancel','target','snapshot'): raise ValueError('Unknown firmware operation') return self.rpc('firmware_' + action, timeout=11 if action=='snapshot' else 4, **parameters) def detect_hall(self): if self.hall_pending: raise ValueError("Hall measurement already pending") self.hall_pending = True self.rpc("hall_start", timeout=0.2, current_a=5) def calibrate_foc(self, max_power_loss_w): self.rpc("foc_start", timeout=0.2, max_power_loss_w=max_power_loss_w) def procedure_result(self): return self.rpc("procedure_result", timeout=0.2) @property def hall_result(self): if not self.hall_pending: return None state = self.rpc("procedure_result", timeout=0.1) result = state.get("result", {}) if state.get("running") or not result.get("completed"): return None return base64.b64decode(result["payload"], validate=True) def close(self): if getattr(self, "bridge", None): self.bridge.close() process, self.process = self.process, None if process is None: return result = {"exit_confirmed": False} try: if process.poll() is None: process.terminate() try: process.wait(timeout=1) except subprocess.TimeoutExpired: process.kill() try: process.wait(timeout=1) except subprocess.TimeoutExpired: # SIGKILL cannot finish uninterruptible kernel I/O. # Retire the owner below without masking the original RPC. pass except OSError as error: result["error"] = str(error)[:256] finally: result["exit_confirmed"] = process.poll() is not None if not result["exit_confirmed"]: with _retiring_lock: _retiring[self.attachment.tty] = process for stream in (process.stdin, process.stdout): if stream: try: stream.close() except OSError as error: result["pipe_error"] = str(error)[:256] return result