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:
@@ -12,62 +12,127 @@ 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"))
|
||||
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.
|
||||
with (config / "engine.log").open("wb") as diagnostic:
|
||||
self.process = subprocess.Popen([str(root / "bin/mission-core-vesc-engine"), "/dev/" + attachment.tty],
|
||||
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:
|
||||
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
|
||||
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):
|
||||
check_attachment(self.attachment)
|
||||
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 or not select.select([self.process.stdout], [], [], max(0, deadline-time.monotonic()))[0]:
|
||||
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 OSError("Native VESC Tool exited")
|
||||
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) > 65536: raise ValueError("Native request exceeds bound")
|
||||
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"),
|
||||
@@ -76,14 +141,19 @@ class NativeLink:
|
||||
"tty": self.attachment.tty}}
|
||||
try:
|
||||
trace["stage"] = "attachment_before"
|
||||
self.check()
|
||||
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")
|
||||
if os.write(self.process.stdin.fileno(), request) != len(request):
|
||||
raise OSError("Native request write incomplete")
|
||||
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"
|
||||
@@ -92,12 +162,14 @@ class NativeLink:
|
||||
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"
|
||||
self.check()
|
||||
if not detached_status: self.check()
|
||||
trace["attachment_after_ms"] = (time.monotonic()-received_at)*1000
|
||||
trace["stage"] = "complete"
|
||||
result = response.get("result")
|
||||
@@ -112,11 +184,13 @@ class NativeLink:
|
||||
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", []))
|
||||
self.close()
|
||||
trace["cleanup"] = self.close()
|
||||
raise
|
||||
|
||||
def query(self, command, timeout=2):
|
||||
@@ -133,13 +207,40 @@ class NativeLink:
|
||||
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
|
||||
@@ -160,12 +261,35 @@ class NativeLink:
|
||||
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
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
try: process.wait(timeout=1)
|
||||
except subprocess.TimeoutExpired:
|
||||
process.kill(); process.wait(timeout=1)
|
||||
for stream in (process.stdin, process.stdout):
|
||||
if stream: stream.close()
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user