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
@@ -4,6 +4,7 @@ import hashlib
import json
from pathlib import Path
import zipfile
from engine_profile import load_profile, header
def build(output):
@@ -11,8 +12,33 @@ def build(output):
files = {"__main__.py": (root / "packaging/native_probe.py").read_bytes(),
"offline_main.cpp": (root / "native/offline_main.cpp").read_bytes(),
"config_export.h": (root / "native/config_export.h").read_bytes(),
"firmware_image.h": (root / "native/firmware_image.h").read_bytes(),
"firmware_source.h": (root / "native/firmware_source.h").read_bytes(),
"bms_native.h": (root / "native/bms_native.h").read_bytes(),
"custom_native.h": (root / "native/custom_native.h").read_bytes(),
"code_native.h": (root / "native/code_native.h").read_bytes(),
"package_native.h": (root / "native/package_native.h").read_bytes(),
"tools_native.h": (root / "native/tools_native.h").read_bytes(),
"swd_native.h": (root / "native/swd_native.h").read_bytes(),
"firmware_native.h": (root / "native/firmware_native.h").read_bytes(),
"config_edit.h": (root / "native/config_edit.h").read_bytes(),
"engine_main.cpp": (root / "native/engine_main.cpp").read_bytes(),
"native_bundle.py": (root / "packaging/native_bundle.py").read_bytes()}
files["bms-settings.xml"] = (root / "native/test-fixtures/bms-settings.xml").read_bytes()
files["native_extensions_check.py"] = (root / "packaging/native_extensions_check.py").read_bytes()
files["native_packages_check.py"] = (root / "packaging/native_packages_check.py").read_bytes()
files["package_archive.py"] = (root / "runtime/package_archive.py").read_bytes()
files["vesc_pkg_all.rcc"] = (root / "build/package-catalog/vesc_pkg_all.rcc").read_bytes()
for name in ("qml_vesc_interface.h", "qml_broker.h", "qml_interactive.h", "sample_data.h", "qml_preview.cpp", "qml_sandbox.h"):
files[name] = (root / "native" / name).read_bytes()
files["native_broker_check.py"] = (root / "packaging/native_broker_check.py").read_bytes()
files["native_samples_check.py"] = (root / "packaging/native_samples_check.py").read_bytes()
files["qml_build.py"] = (root / "packaging/qml_build.py").read_bytes()
files["native_can_check.py"] = (root / "packaging/native_can_check.py").read_bytes()
profile = load_profile()
files["engine-profile.json"] = json.dumps(profile, sort_keys=True).encode()
files["engine_profile.py"] = (root / "packaging/engine_profile.py").read_bytes()
files["engine_profile.h"] = header(profile)
identity = hashlib.sha256(b"".join(k.encode() + v for k, v in sorted(files.items()))).hexdigest()[:24]
output.mkdir(parents=True, exist_ok=True)
path = output / ("mission-core-vesc-native-probe-" + identity + ".pyz")
@@ -0,0 +1,96 @@
{
"schema": "missioncore.vesc.engine-profile/v1",
"rpc_version": 1,
"upstream": {
"repository": "https://github.com/vedderb/vesc_tool",
"version": "7.00",
"commit": "01d5f10901116c311e3fb84d5a1541f663d3ce20",
"source_sha256": "4565ecec4e41e094bcc43127a51970e810aa9080a9d7c025af64632bfd4c0189"
},
"environment": "ubuntu-24.04-amd64",
"firmware_profiles": [
{
"major": 5,
"minor": 2,
"hardware_type": 0,
"test_firmware": 0,
"custom_configs": 0
}
],
"methods": [
"engine",
"query",
"diagnostic",
"configuration",
"procedure_result",
"lease",
"release",
"current",
"rpm",
"duty",
"duty_limited",
"limits",
"foc_start",
"hall_start",
"configuration_preview",
"configuration_apply",
"firmware_begin",
"firmware_chunk",
"firmware_seal",
"firmware_start",
"firmware_status",
"firmware_cancel",
"device_tool",
"bms_read",
"bms_command",
"firmware_target",
"firmware_snapshot",
"custom_read",
"custom_preview",
"custom_apply",
"code_pack",
"code_read",
"code_write",
"code_control",
"code_stats",
"package_unpack",
"code_snapshot",
"sample_start",
"sample_status",
"sample_fetch",
"sample_stop",
"sample_read",
"qml_read"
],
"firmware_formats": [
"bin",
"hex"
],
"bms_profiles": [
{
"major": 6,
"minor": 0
}
],
"bms_protocol_source": {
"repository": "https://github.com/vedderb/vesc_bms_fw",
"commit": "591d57dadb14d4392d4cf859a5187264a8aafed8"
},
"firmware_targets": [
"usb",
"can",
"swd"
],
"code_profiles": [
{
"major": 6,
"minor": 0,
"hardware_type": 0,
"test_firmware": 0
}
],
"control_transports": [
"usb",
"can"
]
}
+69
View File
@@ -0,0 +1,69 @@
"""Reviewed upstream pin and adapter contract; updates never imply hardware acceptance."""
import hashlib
import json
from pathlib import Path
import re
def load_profile(raw=None):
profile = json.loads(raw if raw is not None else Path(__file__).with_name("engine-profile.json").read_bytes())
if (profile.get("schema") != "missioncore.vesc.engine-profile/v1"
or profile.get("rpc_version") != 1 or type(profile["rpc_version"]) is not int
or profile.get("environment") != "ubuntu-24.04-amd64"):
raise ValueError("Unsupported native engine contract")
source = profile.get("upstream", {})
if (source.get("repository") != "https://github.com/vedderb/vesc_tool"
or not re.fullmatch(r"[0-9]+\.[0-9]{2}", source.get("version", ""))
or not re.fullmatch(r"[0-9a-f]{40}", source.get("commit", ""))
or not re.fullmatch(r"[0-9a-f]{64}", source.get("source_sha256", ""))):
raise ValueError("Upstream source must be pinned by commit and archive hash")
profiles = profile.get("firmware_profiles")
fields = {"major", "minor", "hardware_type", "test_firmware", "custom_configs"}
if not isinstance(profiles, list) or not 1 <= len(profiles) <= 64:
raise ValueError("Explicit bounded firmware profiles required")
for item in profiles:
if (not isinstance(item, dict) or set(item) != fields
or any(type(v) is not int or not 0 <= v <= 255 for v in item.values())):
raise ValueError("Invalid firmware acceptance profile")
methods = profile.get("methods")
if (not isinstance(methods, list) or not 1 <= len(methods) <= 128
or len(set(methods)) != len(methods)
or any(not isinstance(v, str) or not re.fullmatch(r"[a-z_]{1,48}", v) for v in methods)
or not {"engine", "query", "configuration"}.issubset(methods)):
raise ValueError("Invalid native operation inventory")
if profile.get("firmware_formats", ["bin"]) not in (["bin"], ["bin", "hex"]):
raise ValueError("Invalid firmware file formats")
if profile.get("firmware_targets",["usb"]) not in (["usb"],["usb","can","swd"]):raise ValueError("Invalid firmware transports")
if profile.get("control_transports", ["usb"]) not in (["usb"], ["usb", "can"]):
raise ValueError("Invalid control transports")
bms = profile.get("bms_profiles", [])
if not isinstance(bms,list) or len(bms)>16 or any(not isinstance(v,dict) or set(v)!={"major","minor"} or any(type(n) is not int or not 0<=n<=255 for n in v.values()) for v in bms):
raise ValueError("Explicit BMS command profiles required")
if bms:
source=profile.get("bms_protocol_source",{})
if source.get("repository")!="https://github.com/vedderb/vesc_bms_fw" or not re.fullmatch(r"[0-9a-f]{40}",source.get("commit","")):
raise ValueError("Pinned BMS protocol source required")
code = profile.get("code_profiles", [])
if code not in ([], [{"major":6,"minor":0,"hardware_type":0,"test_firmware":0}]): raise ValueError("Unreviewed code protocol profile")
return profile
def contract(profile):
raw = json.dumps(profile, sort_keys=True, separators=(",", ":")).encode()
return {"rpc_version": profile["rpc_version"], "profile_sha256": hashlib.sha256(raw).hexdigest(),
"control_transports": profile.get("control_transports", ["usb"]), "code_profiles":profile.get("code_profiles",[]), "firmware_profiles": profile["firmware_profiles"], "methods": profile["methods"],
"firmware_targets":profile.get("firmware_targets",["usb"]), "firmware_formats": profile.get("firmware_formats", ["bin"]), "bms_profiles": profile.get("bms_profiles", [])}
def header(profile):
data = {**profile, "contract": contract(profile)}
literal = json.dumps(json.dumps(data, sort_keys=True, separators=(",", ":")))
return ("// Generated from the reviewed engine profile; do not edit.\n#pragma once\n"
"#include <QJsonDocument>\n#include <QJsonArray>\n#include <QJsonObject>\n"
"static QJsonObject engineProfile() { return QJsonDocument::fromJson(QByteArray(" + literal + ")).object(); }\n"
"static bool nativeFirmwareQualified(int major, int minor, int type, int test, int custom) {\n"
" for (const auto &value : engineProfile().value(\"firmware_profiles\").toArray()) {\n"
" auto p = value.toObject(); if (p.value(\"major\").toInt() == major && p.value(\"minor\").toInt() == minor &&\n"
" p.value(\"hardware_type\").toInt() == type && p.value(\"test_firmware\").toInt() == test &&\n"
" p.value(\"custom_configs\").toInt() == custom) return true;\n"
" } return false;\n}\n").encode()
@@ -0,0 +1,37 @@
"""Restore reviewed official firmware blobs; never selects a moving upstream ref."""
import argparse
import hashlib
import json
from pathlib import Path
import re
import urllib.request
def fetch(output):
manifest=json.loads(Path(__file__).with_name('firmware-catalog.json').read_text())
commit=manifest['commit']
if not re.fullmatch(r'[0-9a-f]{40}',commit) or len(manifest['items'])>512:
raise ValueError('Reviewed catalogue pin required')
output.mkdir(parents=True,exist_ok=True)
for item in manifest['items']:
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+\.bin',item['path']):
raise ValueError('Invalid upstream firmware path')
sha=item['sha256']
if not re.fullmatch(r'[0-9a-f]{64}',sha) or not 256<=item['bytes']<=2*1024**2:
raise ValueError('Invalid firmware size/digest')
path=output/(sha+'.bin')
if path.exists():
data=path.read_bytes()
else:
url='https://raw.githubusercontent.com/vedderb/vesc_fw_archive/'+commit+'/'+item['path']
with urllib.request.urlopen(url,timeout=30) as response:data=response.read(item['bytes']+1)
if len(data)!=item['bytes'] or hashlib.sha256(data).hexdigest()!=sha:
raise ValueError('Pinned firmware bytes changed')
if hashlib.sha1(b'blob '+str(len(data)).encode()+b'\0'+data).hexdigest()!=item['git_blob']:
raise ValueError('Upstream Git blob changed')
if not path.exists():path.write_bytes(data)
return {'commit':commit,'images':len(manifest['items'])}
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--output',type=Path,required=True)
print(json.dumps(fetch(p.parse_args().output)))
@@ -0,0 +1,12 @@
"""Restore the reviewed catalogue bytes; never silently adopt new code."""
from pathlib import Path
import hashlib,json,urllib.request
def main():
root=Path(__file__).resolve().parents[1];pin=json.loads((root/'packaging/package-catalog.json').read_text())
target=root/'build/package-catalog/vesc_pkg_all.rcc'
if target.exists() and hashlib.sha256(target.read_bytes()).hexdigest()==pin['sha256']:return
with urllib.request.urlopen(pin['source'],timeout=30) as response:data=response.read(pin['bytes']+1)
if len(data)!=pin['bytes'] or hashlib.sha256(data).hexdigest()!=pin['sha256']:raise ValueError('Upstream catalogue changed; review and repin explicitly or restore the qualified artifact')
target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(data)
if __name__=='__main__':main()
@@ -0,0 +1,13 @@
Official archived VESC firmware images, unmodified.
Repository: https://github.com/vedderb/vesc_fw_archive
Archive revision: 0030cfa9d6250331436b31a01f006fe0546bf6a6
Firmware version included: 5.02
The catalog records each upstream path, Git blob ID, size and SHA-256.
Upstream firmware source: https://github.com/vedderb/bldc/tree/5.02
Firmware license: GNU GPL version 3 or later (see firmware LICENSE).
No claim of locally reproduced binary/source equivalence is made. These are
upstream archived binaries; the manifest is not manufacturer authentication.
Archive selection does not flash a controller. Firmware updates require a
separate explicit operator action for a compatible board.
Rebuild the installer inputs with packaging/fetch_firmware_catalog.py using
the committed catalog manifest. Runtime downloads are not used.
@@ -0,0 +1,593 @@
{
"schema": "missioncore.vesc.firmware-catalog/v1",
"repository": "https://github.com/vedderb/vesc_fw_archive",
"commit": "0030cfa9d6250331436b31a01f006fe0546bf6a6",
"admitted_versions": [
"5.02"
],
"items": [
{
"id": "fwimg_75a855d02179b810b87e40b7a14002ee",
"path": "5.02/100_250/VESC_default.bin",
"git_blob": "c90ccf8657d3757c22a794e640f23423a08ae846",
"sha256": "cf2eb45caaf6b6514adf392e833c54774c910879d3a82b7fdf9e87369c5533b6",
"bytes": 393208,
"hardware": [
"100_250"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_4aefbbe67d1cfd47e6d5bede921b13e6",
"path": "5.02/100_250/VESC_default_no_hw_limits.bin",
"git_blob": "24bc5beaebd9193c7cd57703e65a4ed18f282998",
"sha256": "229bc4d414864df07ce8cb066c52957fd9ef285225d3ce45007c04c2e752ed0a",
"bytes": 393208,
"hardware": [
"100_250"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_3bf6f675f714c999b0acc2e511546958",
"path": "5.02/410_o_411_o_412/VESC_0005ohm.bin",
"git_blob": "893e8e9df2768b2c9a708f9565ede7c99b6b3f3b",
"sha256": "c2bd00715419ae4a502c085a5ae9b605bfbe8b70e9c9af6cf14e4e20111365e9",
"bytes": 393208,
"hardware": [
"410",
"411",
"412"
],
"version": "5.02",
"name": "VESC_0005ohm.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_80183324bdf6fb609c5a81a28771b31b",
"path": "5.02/410_o_411_o_412/VESC_default.bin",
"git_blob": "8d9a8672aee647bb79e0932e38e27f6bc7361040",
"sha256": "70d491dd289569dd9d1d680a497a8aac66daaa09f9a0738fa8209ebc78b256cc",
"bytes": 393208,
"hardware": [
"410",
"411",
"412"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_939bd113ef079cd9395fc0ea0f9b3186",
"path": "5.02/410_o_411_o_412/VESC_default_no_hw_limits.bin",
"git_blob": "80089b6b99015e0c8c5cebd51f3177dff855f89c",
"sha256": "d412b6996539cd366ee7d128e84be2c62615c50794b3d37e98c4e74ee05e856d",
"bytes": 393208,
"hardware": [
"410",
"411",
"412"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_681a14ef42afe71a902081629d74b2ef",
"path": "5.02/46_o_47/VESC_0005ohm.bin",
"git_blob": "346277633899b3e6521ae81080450f578647165f",
"sha256": "8ca6965370105cd9ce19b75750c85c784d0978d2e8aa0435e853d03adbc4bd92",
"bytes": 393208,
"hardware": [
"46",
"47"
],
"version": "5.02",
"name": "VESC_0005ohm.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_57c7db707659d6a3c83ca1b43f60f3ea",
"path": "5.02/46_o_47/VESC_33k.bin",
"git_blob": "935687e5287cf161b23451f9640c1ee025af784b",
"sha256": "b3c93169808237acbccd17f5edfaf7b3b7d5d804000d3452f226482fcca81807",
"bytes": 393208,
"hardware": [
"46",
"47"
],
"version": "5.02",
"name": "VESC_33k.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_3be270d4c425948c504cbd7fe5483855",
"path": "5.02/46_o_47/VESC_default.bin",
"git_blob": "1e95afa5ca6a56f3dd2204d0700ad14399f3cd20",
"sha256": "8324b8f37666301aa35aa04aa9766b4a9d7b47ef675247c2d1621e40a45c1238",
"bytes": 393208,
"hardware": [
"46",
"47"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_f08494a202c43657f17f1b1b730aa945",
"path": "5.02/48/VESC_default.bin",
"git_blob": "3ad4d01d29deecbfe6f2526471ce3a4ca616135c",
"sha256": "29cb80525dd88adeaa0bb0ca89fe31c47251df9a7d50607a95b2487cab2b4d78",
"bytes": 393208,
"hardware": [
"48"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_248e82b3658efdc981674300f3da5461",
"path": "5.02/60/VESC_default.bin",
"git_blob": "5c2e98823998fee69c46c0a72b803d37442069f5",
"sha256": "5f5c7c876d28e9454d8798b33bbb3844ece52e5ce3bbad2653a025f1c83e4f90",
"bytes": 393208,
"hardware": [
"60"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_579fc598378b6ebc98133bfebd67f43f",
"path": "5.02/60/VESC_default_no_hw_limits.bin",
"git_blob": "5c5f692fa0622207dab86b525a0517677d96d45b",
"sha256": "74ccc48aff7f95ec772d1dc8101b94f41f9f11e588c3afdb9a51d1f67d7cad2a",
"bytes": 393208,
"hardware": [
"60"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_e2e670e40ec08022f880ae6b742d6d01",
"path": "5.02/60_MK3/VESC_default.bin",
"git_blob": "784ad4cfb5e650a7ba0ff7105a21f23f4aa1b4d2",
"sha256": "055cd5d315d52225d5446e17c99c6c33d7e1e80c209d8b8b3832b533703f1a50",
"bytes": 393208,
"hardware": [
"60_MK3"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_c33e1f3a783192f48410c1d920f10992",
"path": "5.02/60_MK3/VESC_default_no_hw_limits.bin",
"git_blob": "a532f14539ceab8b93f747523df8f5947236e4bb",
"sha256": "55f761c5da50e69d84516f29d8a7d8374be63aad4e25404a89edbdc981129ebb",
"bytes": 393208,
"hardware": [
"60_MK3"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_8279ca0cd0e0fd8c8ac7862759badf92",
"path": "5.02/60_MK4/VESC_default.bin",
"git_blob": "43d5946127e3adc87dffb16cf993334c74ac4fb7",
"sha256": "5ddfa85461e5dfe203e183c1b0bfdc392e5d8e310a675e61a5a8da971bd8d413",
"bytes": 393208,
"hardware": [
"60_MK4"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_ceff40c3cb92c34ab9735d7e960ef978",
"path": "5.02/60_MK4/VESC_default_no_hw_limits.bin",
"git_blob": "f2bdf292c1b2ed5f3a012532b4d2aa94757fa31c",
"sha256": "24a93b4a0d3ab2ce5bc6e08129a4c81071f4e448e267b9f5629beed5272703bc",
"bytes": 393208,
"hardware": [
"60_MK4"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_2b9bc59a8361eead3e11da0889404c73",
"path": "5.02/60_MK5/VESC_default.bin",
"git_blob": "0650e356c0304fccd5fcc4ad4d826e65c666b934",
"sha256": "b7116ce5fbb739d2dfac6efdbd6b9e90fe5f9d552d482d65eebee4651dc6075e",
"bytes": 393208,
"hardware": [
"60_MK5"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_c944ee5400afa5e02ef43a175d0603ab",
"path": "5.02/60_MK5/VESC_default_no_hw_limits.bin",
"git_blob": "22bc5b6fac1e188e1bfa93cd077f62833b8af38d",
"sha256": "d75fd10faf81d841811f35d5a49a41eb1bba2e80adf1c9f70e1626bb0f7582e0",
"bytes": 393208,
"hardware": [
"60_MK5"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_d2bd9fd4be5681db97f28095b7b69771",
"path": "5.02/75_300/VESC_default.bin",
"git_blob": "253d5be8030d0a7bb3805cf0acf88ae0c6b53ad1",
"sha256": "b646c7e5c8b6014062833c8a1c96126c2b7b729672579723848bc8f0a3aa68d5",
"bytes": 393208,
"hardware": [
"75_300"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_c6729c906442486769f56f5ff2b43b87",
"path": "5.02/75_300/VESC_default_no_hw_limits.bin",
"git_blob": "c2308f8c2ec9e28ea3af88ead47ae4982ed524c0",
"sha256": "a19af872f4fc422da2bdc34d0ea330b787cc7c27392b4bededaf561db20ccb07",
"bytes": 393208,
"hardware": [
"75_300"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_b9ca797afd58d737be17a2f73b721018",
"path": "5.02/75_300_R2/VESC_default.bin",
"git_blob": "5b79daf0d41008ff7ccad72b00ff8d0dc24f187d",
"sha256": "52c3d9c8d1e7d5670d43d7976a0f02d68c356a666488bcb8d95228e321adf32a",
"bytes": 393208,
"hardware": [
"75_300_R2"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_80c2913ec89ac6673d2be4b247a0aa69",
"path": "5.02/75_300_R2/VESC_default_no_hw_limits.bin",
"git_blob": "ce5d05d2b73f78df5f5a8209588699ff1db90d79",
"sha256": "6d541051f2fcbf946e92db95a4cd573f2f94a3c5fb7cf4d638c9648038b143e9",
"bytes": 393208,
"hardware": [
"75_300_R2"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_2f2d894c2758153f6cf7941b3c928846",
"path": "5.02/75_300_R3/VESC_default.bin",
"git_blob": "b8bdb09c31fc396ba40668e02f1489d533d34f24",
"sha256": "9e1d3c2ccaa12067b604492ebfd1fea2c8768663e7b9b5c45711ad98ca347643",
"bytes": 393208,
"hardware": [
"75_300_R3"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_2e065e7221d31da73cb36d210b9dcc09",
"path": "5.02/75_300_R3/VESC_default_no_hw_limits.bin",
"git_blob": "368d51117b0f92b018a0e5edc82b169ebf5e9c92",
"sha256": "b317f748161d8667f6a36cbeb37e97b3ca959eaaa295aada4bffdc6b6a14946e",
"bytes": 393208,
"hardware": [
"75_300_R3"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_f9fd23f542101759c6cd3d86b1373a4b",
"path": "5.02/A200S_V21/VESC_default.bin",
"git_blob": "ea3af455b80c648cba90de9308a23dc5f94edd6d",
"sha256": "402af86fecd20118762f0d0bd39af63c4b94008deeb3a6500cd8456edd4766a0",
"bytes": 393208,
"hardware": [
"A200S_V21"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_8ae9a0f15636d664557b0143933c7df1",
"path": "5.02/A200S_V22/VESC_default.bin",
"git_blob": "f0cc0d5bbd3c3dca813821c3d80438a183ccf48e",
"sha256": "edab8fbe92aca9d99ac13ed786c690c859b4a74456362b55e566d7ac38547a65",
"bytes": 393208,
"hardware": [
"A200S_V22"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_392b962f7e97e92575391f102b022f39",
"path": "5.02/AXIOM/VESC_default.bin",
"git_blob": "cff1a12ceb7650aa3aeed879e9e946d8058df374",
"sha256": "9d365675f1edcf609efb5a17a80fa1cfd4f6bd2baa597512584e5a9f16587095",
"bytes": 393208,
"hardware": [
"AXIOM"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_ed9bcf99fb6e822056f4aacc94586c3e",
"path": "5.02/DAS_RS/VESC_default.bin",
"git_blob": "8bab886fbbaf3b0fef51d1f55c62254df7b3833a",
"sha256": "8797f475aea54dda11ccea40039fabb40f8faf69ec4cbc64c896d70b3b06bb42",
"bytes": 393208,
"hardware": [
"DAS_RS"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_3c3d4fd4e1c0239a190fc561cef33ddf",
"path": "5.02/HD60/VESC_default.bin",
"git_blob": "6855adb297e6cefe443f7c656621bf9380dfb328",
"sha256": "af3eae52ff6f906cdcecf581c1f66297c09095a63ca700b4c6aa9a648b0cf7e0",
"bytes": 393208,
"hardware": [
"HD60"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_0b76cd76dc14492b1d0314b1b2599a0a",
"path": "5.02/HD60/VESC_default_no_hw_limits.bin",
"git_blob": "cce2905941e677ec21cfb5d37dcee54728f0a898",
"sha256": "1231a6cc61917e773295082ca796515aa6aee9fe5bb12119f94cdb40745d9e49",
"bytes": 393208,
"hardware": [
"HD60"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_25123e904a14be40712992047681f4b2",
"path": "5.02/HD75/VESC_default.bin",
"git_blob": "f2f46d242f0dfd7abf57dd4e7a19510f5b4bcc4a",
"sha256": "d3ce9be5a85ca7a613c85899412ec0cbc4c025c3168baa161ca43d2204bec4e6",
"bytes": 393208,
"hardware": [
"HD75"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_547e9963b050a1d412344d07bda659ed",
"path": "5.02/HD75/VESC_default_no_hw_limits.bin",
"git_blob": "50071916243efbaa6c67cc0bb26c0ae1cfae777a",
"sha256": "e015ec6c4502a3ef2475d77d9f72fb5ec007f08f7a70716f3f9bb74a069d5d84",
"bytes": 393208,
"hardware": [
"HD75"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_8445452db9e2c15e0edafc4232baf6a2",
"path": "5.02/LUNA_BBSHD/VESC_default.bin",
"git_blob": "8ddf65dca569be5b21466b2f1f450ce650a4fbac",
"sha256": "92e938a56a164681731a89957c16d62e6b86e85203f0d0ddcb920dcb9406c8c7",
"bytes": 393208,
"hardware": [
"LUNA_BBSHD"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_b037176c63f44af2d112be7c46b651ef",
"path": "5.02/STORMCORE_100D/VESC_default.bin",
"git_blob": "ca67541c042126b58c875fb6fb7b5d19bfa1ee23",
"sha256": "633cbeb6fa11bfefdc98ac1b6b2765fe080ec56a5272c8219b6e9422b6ee4f22",
"bytes": 393208,
"hardware": [
"STORMCORE_100D"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_510bc5346a26ab5abe00598b9e3a7a15",
"path": "5.02/STORMCORE_100D/VESC_default_no_hw_limits.bin",
"git_blob": "d2cb084eb6e2f10b4e33ab826b4d84ff2cb1bcb6",
"sha256": "66c19f693ac1018de5818fa7856629133ad4d389cab3366d202495c6ee4f352b",
"bytes": 393208,
"hardware": [
"STORMCORE_100D"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_3fb8cbee44e0ef14e11558f272d2a5ad",
"path": "5.02/STORMCORE_100S/VESC_default.bin",
"git_blob": "06adfb19ab9981c327aee4d6a71ae46c27778c65",
"sha256": "4167f6c34fa3c2267cee15f593b0b93d14fd7ae032049fb944e3f464c90b4434",
"bytes": 393208,
"hardware": [
"STORMCORE_100S"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_af09ed784286b4c5fa82baa72d43881e",
"path": "5.02/STORMCORE_100S/VESC_default_no_hw_limits.bin",
"git_blob": "12d545cb0afe8a282948cfd7288658e9d65f8a79",
"sha256": "afeada4f382a354a709bb7a2849bbab7bde8b8144479d2dcffabd870e8ba33e3",
"bytes": 393208,
"hardware": [
"STORMCORE_100S"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_c327a275325fe87b693611099625e451",
"path": "5.02/STORMCORE_60D/VESC_default.bin",
"git_blob": "25907b4cfcabf5277701d933ef837e7c991540bd",
"sha256": "3867b3f60ca650d8dd742d532b46f4475b347d6e623d9555a140e386caf2f453",
"bytes": 393208,
"hardware": [
"STORMCORE_60D"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_652b83aefe9aa2f1a2fb5246164c8414",
"path": "5.02/STORMCORE_60D/VESC_default_no_hw_limits.bin",
"git_blob": "b2a220c858eeb5b401fc18642d9f3ca938a691f9",
"sha256": "89945b83a12f3f91eeff2c42d115830bc9f30817d05c513b1f6cd99f1a1c786a",
"bytes": 393208,
"hardware": [
"STORMCORE_60D"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
},
{
"id": "fwimg_cb2a8e9dc5d125f6b89db1da8edc7e2e",
"path": "5.02/UAVC_OMEGA/VESC_default.bin",
"git_blob": "cf9c8f8c8f951a02195f8405ab1fb287dc2b0bce",
"sha256": "d014be805e06237cca9057aae6e5ace96546905d6a0256633675e4a1fb9e3b77",
"bytes": 393208,
"hardware": [
"UAVC_OMEGA"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_21e86da15b810624c5c542ae425badd6",
"path": "5.02/UNITY/VESC_default.bin",
"git_blob": "ffe19f1f13bc6137aca8b78a5825b58ac43507a1",
"sha256": "17042fd9fb0f6455ff886eccb03ec2dced6d408d7895849eaa45f3b5420350ee",
"bytes": 393208,
"hardware": [
"UNITY"
],
"version": "5.02",
"name": "VESC_default.bin",
"kind": "firmware",
"hardware_limits": true
},
{
"id": "fwimg_ce34a332bbe40e7ada15fdb5bb4e6109",
"path": "5.02/UNITY/VESC_default_no_hw_limits.bin",
"git_blob": "d08e9d3892837078a251f8752ce4859ac496a51e",
"sha256": "3f6efc4ce7483c65d7005a25e7e503539c29ffbd09749616654aa9d78d6971aa",
"bytes": 393208,
"hardware": [
"UNITY"
],
"version": "5.02",
"name": "VESC_default_no_hw_limits.bin",
"kind": "firmware",
"hardware_limits": false
}
]
}
@@ -27,11 +27,14 @@ ProtectKernelTunables=yes
ProtectKernelModules=yes
ProtectControlGroups=yes
RestrictSUIDSGID=yes
RestrictAddressFamilies=AF_UNIX
# Native Tool and bridge communicate on loopback inside this private network.
RestrictAddressFamilies=AF_UNIX AF_INET
DevicePolicy=closed
DeviceAllow=char-ttyACM rw
MemoryMax=512M
MemoryMax=1G
TasksMax=64
LogRateLimitIntervalSec=30s
LogRateLimitBurst=60
[Install]
WantedBy=multi-user.target
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,100 @@
"""Real Qt signals, sandbox and read-intent bounds, with synthetic replies only."""
import base64
import json
import os
import select
import struct
import subprocess
import time
def broker(binary, env, archive, report):
p = subprocess.Popen(
[str(binary)],
env=env,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
bufsize=0,
)
buffer = b""
def call(value):
nonlocal buffer
p.stdin.write(json.dumps(value).encode() + b"\n")
deadline = time.monotonic() + 7
while b"\n" not in buffer:
assert select.select([p.stdout], [], [], max(0, deadline - time.monotonic()))[0], (
"QML broker timeout"
)
chunk = os.read(p.stdout.fileno(), 65536)
assert chunk, "QML exited"
buffer += chunk
assert len(buffer) < 800 * 1024
line, buffer = buffer.split(b"\n", 1)
v = json.loads(line)
assert (
v["ok"]
and v["hardware_access"] is False
and v["sandbox_verified"]
and v["broker"]
and not v["snapshot_only"]
), v.get("error")
return v
try:
source = """import QtQuick 2.5
Rectangle { id: root; property real volts: 0; color: volts > 40 ? "#246834" : "#263343"
Connections { target: VescIf.commands(); onValuesReceived: { root.volts = values.v_in; } }
MouseArea { anchors.fill: parent; onClicked: {
if (VescIf.isPortConnected() && VescIf.fwRx()) { VescIf.commands().getValues(); VescIf.commands().getImuData(511); }
VescIf.commands().setRpm(99); VescIf.commands().sendTerminalCmd("help"); } }
}"""
first = call(
{
**archive,
"source": source,
"width": 640,
"height": 480,
"standalone": False,
"broker": True,
"interactive": True,
"values": base64.b64encode(bytes([4]) + bytes(95)).decode(),
}
)
clicked = call(
{
"op": "frame",
"events": [{"kind": "down", "x": 20, "y": 20}, {"kind": "up", "x": 20, "y": 20}],
}
)
assert {"command": 4} in clicked["read_requests"] and {
"command": 65,
"mask": 511,
} in clicked["read_requests"]
assert 8 in clicked["blocked_codes"] and 20 in clicked["blocked_codes"]
raw = bytes([4]) + struct.pack(
">hhiiiihihiiiiiiB", 250, 250, 0, 0, 0, 0, 0, 0, 480, 0, 0, 0, 0, 0, 0, 0
)
replied = call({"op": "frame", "events": [], "packets": [base64.b64encode(raw).decode()]})
assert replied["png"] != first["png"], "Fresh real Commands signal did not update QML"
assert all(
x["command"] in (0, 4, 14, 17, 31, 32, 33, 65, 96) for x in replied["read_requests"]
)
p.stdin.write(b'{"op":"close"}\n')
p.wait(timeout=3)
assert p.returncode == 0
report["checks"].append(
{
"id": "qml-broker-read-signals-write-denied-no-transport",
"ok": True,
"hardware_access": False,
}
)
finally:
if p.poll() is None:
p.kill()
p.wait(timeout=3)
p.stdin.close()
p.stdout.close()
+28 -13
View File
@@ -12,11 +12,14 @@ import re
import shutil
import subprocess
import tarfile
from engine_profile import load_profile, contract
SYSTEM = {"libc.so.6", "libm.so.6", "libpthread.so.0", "libdl.so.2", "librt.so.1", "libresolv.so.2", "ld-linux-x86-64.so.2"}
def build(engine, sysroot, source, output):
def build(engine, sysroot, source, output, qml_sysroot):
profile = load_profile((engine.parent / "engine-profile.json").read_bytes())
upstream = profile["upstream"]
output.mkdir(mode=0o700, exist_ok=False)
staging = output / "payload"
(staging / "bin").mkdir(parents=True)
@@ -27,9 +30,17 @@ def build(engine, sysroot, source, output):
qtlib = sysroot / "usr/lib/x86_64-linux-gnu"
plugin = qtlib / "qt5/plugins/platforms/libqoffscreen.so"
shutil.copyfile(plugin, staging / "plugins/platforms/libqoffscreen.so")
renderer = staging / "bin/mission-core-vesc-qml-preview"
shutil.copyfile(engine.parent / renderer.name, renderer); renderer.chmod(0o755)
qml = qml_sysroot / "usr/lib/x86_64-linux-gnu/qt5/qml"
shutil.copytree(qml, staging / "qml")
shutil.copytree(qml_sysroot / "usr/share/fonts/truetype/dejavu", staging / "fonts")
qml_plugins = list((staging / "qml").rglob("*.so"))
if len(qml_plugins) < 5: raise RuntimeError("QML runtime modules missing")
closure_inputs = [engine, renderer, plugin, *qml_plugins]
env = dict(os.environ, LD_LIBRARY_PATH=str(qtlib), LC_ALL="C")
sources = {}
for executable in (engine, plugin):
for executable in closure_inputs:
result = subprocess.run(["/usr/bin/ldd", str(executable)], env=env, capture_output=True, text=True, check=True).stdout
if "not found" in result: raise RuntimeError("Native runtime dependency missing")
for name, path in re.findall(r"^\s*(\S+) => (/[\S]+) \(", result, re.MULTILINE):
@@ -41,7 +52,7 @@ def build(engine, sysroot, source, output):
env.update(LD_LIBRARY_PATH=str(staging / "lib"), QT_PLUGIN_PATH=str(staging / "plugins"),
QT_QPA_PLATFORM="offscreen", XDG_CONFIG_HOME=str(output / "config"), XDG_CACHE_HOME=str(output / "cache"))
# All non-glibc ELF dependencies must now resolve inside the shipped payload.
for executable in (binary, staging / "plugins/platforms/libqoffscreen.so"):
for executable in [binary, renderer, staging / "plugins/platforms/libqoffscreen.so", *qml_plugins]:
result = subprocess.run(["/usr/bin/ldd", str(executable)], env=env, capture_output=True, text=True, check=True).stdout
if "not found" in result: raise RuntimeError("Bundled native closure incomplete")
for name, path in re.findall(r"^\s*(\S+) => (/[\S]+) \(", result, re.MULTILINE):
@@ -52,19 +63,22 @@ def build(engine, sysroot, source, output):
responses = [json.loads(line) for line in proc.stdout.splitlines()]
if len(responses) != 2 or not responses[0]["ready"] or responses[1]["result"]["connected"]:
raise RuntimeError("Bundled engine acceptance failed")
info = responses[1]["result"]
if info.get("version") != upstream["version"] or info.get("commit") != upstream["commit"] or info.get("contract") != contract(profile):
raise RuntimeError("Bundled engine version or contract differs from reviewed profile")
(output / "offline.stdout").write_bytes(proc.stdout)
(output / "offline.stderr").write_bytes(proc.stderr)
(staging / "licenses").mkdir()
shutil.copyfile(source / "LICENSE", staging / "licenses/VESC-Tool-LICENSE")
(staging / "licenses/UPSTREAM-SOURCE.txt").write_text(
"VESC Tool 7.00, unmodified upstream sources and resources:\n"
"https://github.com/vedderb/vesc_tool/tree/01d5f10901116c311e3fb84d5a1541f663d3ce20\n"
"Source archive SHA-256: 4565ecec4e41e094bcc43127a51970e810aa9080a9d7c025af64632bfd4c0189\n"
"The process adapter source is included alongside this notice.\n")
for name in ("engine_main.cpp", "config_export.h"):
f"VESC Tool {upstream['version']}, unmodified upstream sources and resources:\n"
f"{upstream['repository']}/tree/{upstream['commit']}\n"
f"Source archive SHA-256: {upstream['source_sha256']}\n"
"The process adapter source and release profile are included alongside this notice.\n")
for name in ("qml_vesc_interface.h", "qml_broker.h", "qml_interactive.h", "sample_data.h", "qml_preview.cpp", "qml_sandbox.h", "engine_main.cpp", "config_export.h", "config_edit.h", "firmware_image.h", "firmware_source.h", "firmware_native.h", "swd_native.h", "tools_native.h", "bms_native.h", "custom_native.h", "code_native.h", "package_native.h", "engine_profile.h", "engine-profile.json"):
shutil.copyfile(engine.parent / name, staging / "licenses" / name)
# Preserve dependency notices available in the private signed-package sysroot.
for index, path in enumerate(sorted((sysroot / "usr/share/doc").glob("*/copyright"))):
for index, path in enumerate(sorted((sysroot / "usr/share/doc").glob("*/copyright")) + sorted((qml_sysroot / "usr/share/doc").glob("*/copyright"))):
shutil.copyfile(path, staging / "licenses" / (path.parent.name + ".copyright"))
# Host libraries copied into the closure retain their distribution notices.
for library in sources.values():
@@ -80,8 +94,9 @@ def build(engine, sysroot, source, output):
with tarfile.open(archive, "w:gz") as stream:
for path in sorted(staging.rglob("*")):
if path.is_file(): stream.add(path, arcname=str(path.relative_to(staging)))
report = {"schema":"missioncore.vesc.native-runtime/v1", "upstream_version":"7.00",
"upstream_commit":"01d5f10901116c311e3fb84d5a1541f663d3ce20", "os":"ubuntu-24.04-amd64",
report = {"schema":"missioncore.vesc.native-runtime/v1", "upstream_version":upstream["version"],
"upstream_commit":upstream["commit"], "upstream_source_sha256":upstream["source_sha256"],
"engine_contract":contract(profile), "os":profile["environment"],
"file":archive.name, "bytes":archive.stat().st_size, "sha256":hashlib.sha256(archive.read_bytes()).hexdigest(),
"engine_sha256":hashlib.sha256(binary.read_bytes()).hexdigest(), "files":metadata,
"host_libraries":sorted(SYSTEM), "offline_verified":True, "hardware_qualified":False,
@@ -91,5 +106,5 @@ def build(engine, sysroot, source, output):
if __name__ == "__main__":
parser=argparse.ArgumentParser()
for name in ("engine","sysroot","source","output"):parser.add_argument("--"+name,type=Path,required=True)
args=parser.parse_args();build(args.engine,args.sysroot,args.source,args.output)
for name in ("engine","sysroot","source","output","qml-sysroot"):parser.add_argument("--"+name,type=Path,required=True)
args=parser.parse_args();build(args.engine,args.sysroot,args.source,args.output,args.qml_sysroot)
@@ -0,0 +1,99 @@
"""Inert loopback peer for the native CAN transport. No SDK/device access."""
import base64
import time
from pathlib import Path
import binascii
import json
import select
import socket
import subprocess
import sys
import threading
def framed(payload):
width=1 if len(payload)<256 else 2
return bytes([width+1])+len(payload).to_bytes(width,"big")+payload+binascii.crc_hqx(payload,0).to_bytes(2,"big")+b"\x03"
def main():
listener=socket.socket()
listener.bind(("127.0.0.1",0));listener.listen(1);listener.settimeout(5)
frames=[];errors=[]
archive=json.loads(Path(sys.argv[2]).read_text())
configs={14:base64.b64decode(archive["configs"]["motor"]["payload"]),17:base64.b64decode(archive["configs"]["application"]["payload"])}
def peer():
try:
conn,_=listener.accept()
with conn:
conn.settimeout(5)
buffer=b""
while True:
data=conn.recv(16384)
if not data:break
buffer+=data
while len(buffer)>=2:
width=buffer[0]-1
if width not in (1,2):raise ValueError("Invalid framing")
if len(buffer)<width+1:break
size=int.from_bytes(buffer[1:width+1],"big")
end=width+1+size
if len(buffer)<end+3:break
payload=buffer[width+1:end]
if buffer[end+2]!=3 or binascii.crc_hqx(payload,0)!=int.from_bytes(buffer[end:end+2],"big"):
raise ValueError("Invalid CRC")
buffer=buffer[end+3:];frames.append(payload.hex())
if payload[0]==0:
conn.sendall(framed(b"\x00\x05\x02SYNTHETIC\x00"+bytes([1])*12+b"\x00\x00\x00\x00"))
elif payload[0] in configs:conn.sendall(framed(configs[payload[0]]))
elif payload==b"\xffMCBR":conn.sendall(framed(payload))
except Exception as e:errors.append(str(e))
thread=threading.Thread(target=peer,daemon=True);thread.start()
process=subprocess.Popen([sys.argv[1],"--can-bridge="+str(listener.getsockname()[1])],
stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
def receive():
if not select.select([process.stdout],[],[],5)[0]:raise ValueError("Native reply timeout")
line=process.stdout.readline()
if not line:raise ValueError(process.stderr.read().decode())
return json.loads(line)
try:
hello=receive()
assert hello["ready"] and hello["engine"]["connected"] and hello["engine"]["firmware_admitted"],hello
requests=[{"id":1,"method":"query","command":0,"timeout_ms":1000},
{"id":2,"method":"lease"},{"id":3,"method":"rpm","erpm":500},
{"id":4,"method":"release"}]
for request in requests:
process.stdin.write(json.dumps(request).encode()+b"\n");process.stdin.flush()
response=receive()
assert response["id"]==request["id"] and response["ok"],response
def rpc(method,**parameters):
process.stdin.write(json.dumps({"id":20,"method":method,**parameters}).encode()+b"\n");process.stdin.flush()
return receive()
configuration=rpc("configuration")
assert configuration["ok"],configuration
motor={p["name"]:p["value"] for p in configuration["result"]["motor"]["parameters"]}
ceiling=max(motor["l_current_max"]*motor["l_current_max_scale"],-motor["l_current_min"]*motor["l_current_min_scale"])
assert ceiling>30, "Qualification fixture must exercise above-30-A config"
assert rpc("lease")["ok"]
rejected=rpc("duty_limited",duty=.5,current_a=ceiling-1)
assert not rejected["ok"],rejected
accepted=rpc("duty_limited",duty=.5,current_a=ceiling)
assert accepted["ok"] and accepted["control"]["output_kind"]=="duty",accepted
assert rpc("lease")["ok"]
mark=len(frames)
zero=rpc("duty_limited",duty=0,current_a=ceiling)
assert zero["ok"] and "0500000000" in frames[mark:],(zero,frames[mark:])
assert "0600000000" not in frames[mark:],frames[mark:]
previous=zero["control"]["watchdog_trips"]
time.sleep(.27)
expired=rpc("query",command=0,timeout_ms=1000)
assert expired["ok"] and expired["control"]["watchdog_trips"]>previous,expired
assert expired["control"]["output_kind"]=="watchdog_release",expired
assert not rpc("duty_limited",duty=.5,current_a=ceiling)["ok"]
process.stdin.close();process.wait(timeout=5);thread.join(5)
assert process.returncode==0 and not errors,(process.returncode,errors)
assert any(v.startswith("08") for v in frames),frames
assert frames.count("ff4d434252")>=3,frames
print(json.dumps({"ok":True,"hardware_access":False,"transport":"private-loopback","frames":frames}))
finally:
if process.poll() is None:process.kill();process.wait(timeout=5)
listener.close()
if __name__=="__main__":main()
+4 -1
View File
@@ -24,7 +24,10 @@ def check(root):
replies = [json.loads(line) for line in result.stdout.splitlines()]
if (len(replies) != 2 or not replies[0]["ready"] or not replies[1]["ok"]
or replies[1]["result"]["hardware_enabled"] or replies[1]["result"]["connected"]
or replies[1]["result"]["commit"] != manifest["upstream_commit"]):
or replies[1]["result"]["commit"] != manifest["upstream_commit"]
or replies[1]["result"]["version"] != manifest["upstream_version"]
or replies[1]["result"].get("contract") != manifest.get("engine_contract")
or manifest.get("engine_contract", {}).get("rpc_version") != 1):
raise RuntimeError("Native engine offline check failed")
print(json.dumps({"ok":True, "upstream_commit":manifest["upstream_commit"], "hardware_access":False}))
@@ -0,0 +1,28 @@
"""Offline qualification against pinned upstream BMS schema and CodeLoader."""
import base64
import json
def check_extensions(execute,target,raw,root,report):
b64=lambda b:base64.b64encode(b).decode()
original=json.loads(raw)
def run(name,fields,expected=0):
value={**original,**fields}
output=json.loads(execute(name,[str(target)],json.dumps(value).encode(),expected=expected))
if output['ok']!=(expected==0) or output['hardware_access']:raise RuntimeError('Native extension qualification failed: '+name)
report['checks'].append({'id':name,'ok':True,'hardware_access':False})
return output
schema=(root/'bms-settings.xml').read_bytes()
value=run('custom-bms-schema',{'custom_schema':b64(schema)})
config=value['custom_configuration']
assert len(config['parameters'])>=32 and config['round_trip_exact'] and config['groups']
for name,source,expected in [('typed',{'changes':{'max_bal_ch':2}},0),('xml',{'xml':config['xml']},0),('unknown',{'changes':{'missing_param':12}},1),('bounds',{'changes':{'max_bal_ch':100000}},1),('entity',{'xml':'<!DOCTYPE x [<!ENTITY z SYSTEM "file:///etc/passwd">]><CustomConfiguration><max_bal_ch>&z;</max_bal_ch></CustomConfiguration>'},1)]:
run('custom-'+name,{'custom_schema':b64(schema),'custom_edit':source},expected)
run('custom-schema-dtd',{'custom_schema':b64(b'<!DOCTYPE x [<!ENTITY z SYSTEM "file:///etc/passwd">]><ConfigParams>&z;</ConfigParams>')},1)
for kind,source,files in [('lisp','(+ 1 2)',{}),('lisp','(import "test.bin" \'blob)\n(print blob)',{'test.bin':b64(b'\x00\xff\x01')}),('qml','import QtQuick 2.12\nItem { width: 200; height: 100 }',{})]:
run('code-'+kind+'-'+str(len(files)),{'code_project':{'kind':kind,'source':source,'imports':files,'fullscreen':True}})
for label,source,files in [('parent','(import "../secret" \'x)',{}),('absolute','(import "/etc/passwd" \'x)',{}),('package','(import "pkg::code@x" \'x)',{}),('missing','(import "a.bin" \'x)',{}),('duplicate','(import "a.bin" \'x)\n(import "b.bin" \'x)',{'a.bin':b64(b'a'),'b.bin':b64(b'b')}),('nul','abc\0def',{}),('oversize','x'*122881,{})]:
run('code-reject-'+label,{'code_project':{'kind':'lisp','source':source,'imports':files,'fullscreen':False}},1)
run('code-reject-checksum',{'code_image':{'kind':'lisp','image':b64(b'\0'*10)}},1)
run('code-reject-import-range',{'code_decode':{'kind':'lisp','payload':b64(b'x\0\0\1tag\0\xff\xff\xff\xff\0\0\0\4')}},1)
run('code-reject-qml-inflate',{'code_decode':{'kind':'qml','payload':b64(b'\x7f\xff\xff\xffAAAA')}},1)
@@ -0,0 +1,27 @@
"""Offline upstream package codec and pure compatibility function qualification."""
import base64,json,zlib,struct
def check_packages(execute,target,raw,root,report):
from package_archive import archive
b64=lambda b:base64.b64encode(b).decode()
original=json.loads(raw)
fw={'hardware':'75_300_R2','hardware_type':0,'major':6,'minor':0,'firmware_name':''}
def run(name,package,identity=fw,expected=0):
result=json.loads(execute(name,[str(target)],json.dumps({**original,'package':{'data':b64(package),'identity':identity,'export_library':name.startswith('pkg-official-')}}).encode(),expected=expected))
assert result['ok']==(expected==0) and not result['hardware_access']
report['checks'].append({'id':name,'ok':True,'hardware_access':False})
return result.get('package')
def pkg(desc='',extra=b''):
raw=b'VESC Packet\0'+b'name\0'+struct.pack('>i',4)+b'Test'+b'pkgDescQml\0'+struct.pack('>i',len(desc.encode()))+desc.encode()+extra
return struct.pack('>I',len(raw))+zlib.compress(raw)
assert run('pkg-compatible',pkg('Item { function isCompatible(p) {return p.hwTypeStr()=="VESC" && p.major==6;} }'))['compatible'] is True
assert run('pkg-incompatible',pkg('Item { function isCompatible(p) {return p.hwTypeStr()=="custom module";} }'))['compatible'] is False
for label,source in [('loop','while(true){}'),('no-host','return typeof Qt!=="undefined" || typeof XMLHttpRequest!=="undefined" || typeof VescIf!=="undefined";'),('nonboolean','return "yes";'),('throw','throw Error("failed");')]:
value=run('pkg-js-'+label,pkg('Item { Component.onCompleted: {throw "never";} function isCompatible(p) {'+source+'} }'))['compatible']
assert value is (False if label=='no-host' else None)
for label,data in [('duplicate',pkg(extra=b'name\0\0\0\0\1x')),('length',pkg(extra=b'bad\0\xff\xff\xff\xff')),('flag',pkg(extra=b'qmlIsFullscreen\0\0\0\0\2\0\0')),('inflate',b'\0\0\0\1'+zlib.compress(b'x'*100000))]:run('pkg-reject-'+label,data,expected=1)
entries=archive((root/'vesc_pkg_all.rcc').read_bytes())
for i,(name,data) in enumerate(entries.items()):
value=run('pkg-official-'+str(i),data)
assert value['name'] and set(value['images'])=={'lisp','qml'}
if not value['fits']:assert value['images']=={'lisp':'','qml':''}
+175 -9
View File
@@ -16,8 +16,7 @@ import subprocess
import time
import zipfile
COMMIT = "01d5f10901116c311e3fb84d5a1541f663d3ce20"
UPSTREAM_SHA256 = "4565ecec4e41e094bcc43127a51970e810aa9080a9d7c025af64632bfd4c0189"
from engine_profile import load_profile, contract
def digest(path):
@@ -25,6 +24,10 @@ def digest(path):
def run(args):
with zipfile.ZipFile(args.artifact) as bundle:
profile = load_profile(bundle.read("engine-profile.json"))
COMMIT = profile["upstream"]["commit"]
UPSTREAM_SHA256 = profile["upstream"]["source_sha256"]
release = platform.freedesktop_os_release()
if os.geteuid() == 0 or (release.get("ID"), release.get("VERSION_ID"), platform.machine()) != ("ubuntu", "24.04", "x86_64"):
raise RuntimeError("Unprivileged Ubuntu 24.04 amd64 required")
@@ -33,7 +36,7 @@ def run(args):
if limit == "max" or int(limit) > 3 * 1024**3:
raise RuntimeError("A bounded user scope with MemoryMax <= 3G is required")
previous = json.loads(args.upstream_report.read_text())
if previous.get("state") != "complete" or previous.get("source_sha256") != UPSTREAM_SHA256:
if previous.get("state") != "complete" or previous.get("source_sha256") != UPSTREAM_SHA256 or previous.get("source_commit") != COMMIT:
raise RuntimeError("Unqualified upstream build")
upstream = Path(previous["binary"])
if digest(upstream) != previous["binary_sha256"]:
@@ -48,7 +51,7 @@ def run(args):
if any(not re.fullmatch(r"[A-Za-z0-9_./-]+", str(p)) for p in (root, source)):
raise RuntimeError("Build paths must be make-safe")
with zipfile.ZipFile(args.artifact) as bundle:
for name in ("offline_main.cpp", "config_export.h", "engine_main.cpp", "native_bundle.py"):
for name in ("native_can_check.py", "native_broker_check.py", "native_samples_check.py", "qml_vesc_interface.h", "qml_broker.h", "qml_interactive.h", "sample_data.h", "qml_preview.cpp", "qml_sandbox.h", "qml_build.py", "bms-settings.xml", "native_extensions_check.py", "native_packages_check.py", "package_archive.py", "vesc_pkg_all.rcc", "offline_main.cpp", "config_export.h", "config_edit.h", "firmware_image.h", "firmware_source.h", "firmware_native.h", "swd_native.h", "tools_native.h", "bms_native.h", "custom_native.h", "code_native.h", "package_native.h", "engine_main.cpp", "native_bundle.py", "engine_profile.py", "engine_profile.h", "engine-profile.json"):
(root / name).write_bytes(bundle.read(name))
report = {"schema": "missioncore.vesc.native-probe/v1", "state": "running",
"started_at": datetime.now(timezone.utc).isoformat(), "monotonic_started": time.monotonic(),
@@ -101,7 +104,7 @@ def run(args):
"mission-core-native-probe:\n"
"\t$(CXX) -c $(CXXFLAGS) $(INCPATH) -o " + str(root / "offline_main.o") + " " + str(root / "offline_main.cpp") + "\n"
"\t$(LINK) $(LFLAGS) -o " + str(target) + " " + str(root / "offline_main.o") +
" $(filter-out build/lin/obj/main.o,$(OBJECTS)) $(OBJCOMP) $(LIBS)\n")
" $(filter-out build/lin/obj/main.o,$(OBJECTS)) $(OBJCOMP) $(LIBS) -lz\n")
execute("compile-link", ["/usr/bin/make", "-f", str(wrapper), "mission-core-native-probe"], timeout=180)
report["binary_sha256"] = digest(target)
for index, archive in enumerate(args.archives):
@@ -126,6 +129,101 @@ def run(args):
"xml_equivalent_by_upstream_comparison": True,
"xml_binary_exact": all(native[k]["xml_round_trip_exact"] for k in ("motor", "application")),
"legacy_power_loss_correction": True})
# Exercise the same native preparation used online, without any transport.
edits = [
("typed", {"changes": {"l_current_max": 20.0}}, 0),
("restore", {"payload": json.loads(raw)["configs"]["motor"]["payload"]}, 0),
("xml", {"xml": native["motor"]["xml"]}, 0),
("unknown-field", {"changes": {"not_a_parameter": 1}}, 1),
("outside-range", {"changes": {"l_current_max": 1e12}}, 1),
("wrong-type", {"changes": {"l_current_max": "20"}}, 1),
("bad-enum", {"changes": {"motor_type": 500}}, 1),
("xml-unknown", {"xml": "<MCConfiguration><unknown>1</unknown></MCConfiguration>"}, 1),
("xml-metadata", {"xml": "<MCConfiguration><motor_brand>Changed</motor_brand></MCConfiguration>"}, 1),
("xml-nan", {"xml": "<MCConfiguration><l_current_max>NaN</l_current_max></MCConfiguration>"}, 1),
("xml-duplicate", {"xml": "<MCConfiguration><l_current_max>20</l_current_max><l_current_max>30</l_current_max></MCConfiguration>"}, 1),
("xml-entity", {"xml": '<!DOCTYPE MCConfiguration [<!ENTITY x "20">]><MCConfiguration><l_current_max>&x;</l_current_max></MCConfiguration>'}, 1),
]
for label, source_edit, expected in edits:
value = json.loads(raw); value["edit"] = {"kind": "motor", "source": source_edit}
edited = json.loads(execute("edit-%s-%d" % (label, index), [str(target)], json.dumps(value).encode(), expected=expected))
if edited.get("ok") != (expected == 0) or edited.get("hardware_access"):
raise RuntimeError("Native edit qualification mismatch")
if label == "typed" and not any(p["name"] == "l_current_max" and p["after"] == 20 for p in edited["edit"]["changes"]):
raise RuntimeError("Native edit did not preserve requested value")
if label == "restore" and edited["edit"]["changes"]:
raise RuntimeError("Restoring the identical backup changed parameters")
report["checks"].append({"id": "edit-%s-%d" % (label, index), "ok": True})
# Test exactly the file inspector used by the USB owner, but with
# synthetic vectors and no transport or firmware upload.
image = bytes.fromhex("0000022001010008") + bytes(1016)
for label, data, kind, expected in (
("raw",image,"firmware",0), ("bootloader",image,"bootloader",0),
("short",image[:100],"firmware",1), ("stack",bytes(1024),"firmware",1),
("reset",image[:4]+bytes(4)+image[8:],"firmware",1),
("large-bootloader",image+bytes(65536),"bootloader",1),
("kind",image,"other",1)):
value = json.loads(raw)
value["firmware_image"] = {"data":base64.b64encode(data).decode(),"kind":kind}
inspected = json.loads(execute("image-%s-%d" % (label,index),[str(target)],json.dumps(value).encode(),expected=expected))
if inspected.get("ok") != (expected == 0) or inspected.get("hardware_access"):
raise RuntimeError("Firmware image inspection qualification failed")
if expected == 0 and inspected["firmware_image"]["sha256"] != hashlib.sha256(data).hexdigest():
raise RuntimeError("Firmware image digest changed")
# Original HexFile normalization behind strict container/address bounds.
def hexline(address, kind, data=b''):
record=bytes([len(data),address>>8,address&255,kind])+data
return b':'+(record+bytes([-sum(record)&255])).hex().upper().encode()+b'\n'
def ihex(data, base=0x08000000):
return hexline(0,4,(base>>16).to_bytes(2,'big'))+b''.join(hexline(i,0,data[i:i+16]) for i in range(0,len(data),16))+hexline(0,1)
valid=ihex(image)
gap=hexline(0,4,b'\x08\x00')+hexline(0,0,image[:16])+hexline(1008,0,image[-16:])+hexline(0,1)
reordered=hexline(0,4,b'\x08\x00')+hexline(1008,0,image[-16:])+hexline(0,0,image[:16])+hexline(0,1)
duplicate=valid.replace(hexline(0,1),hexline(0,0,image[:16])+hexline(0,1))
for label,data,kind,expected in [
('valid',valid,'firmware',0),('crlf',valid.replace(b'\n',b'\r\n'),'firmware',0),
('gap',gap,'firmware',0),('reordered',reordered,'firmware',0),
('checksum',valid.replace(b':020000040800F2',b':020000040800F3'),'firmware',1),
('junk',valid.replace(b':10',b':1G',1),'firmware',1),('overlap',duplicate,'firmware',1),
('truncated',valid.replace(hexline(0,1),b''),'firmware',1),
('trailing',valid+hexline(16,0,image[16:32]),'firmware',1),
('wrong-base',ihex(image,0x08010000),'firmware',1),
('sparse',valid.replace(hexline(0,1),hexline(0,4,b'\x09\x00')+hexline(0,0,image[:16])+hexline(0,1)),'firmware',1),
('bootloader-address',valid,'bootloader',1)]:
value=json.loads(raw);value['firmware_image']={'data':base64.b64encode(data).decode(),'kind':kind,'format':'hex'}
inspected=json.loads(execute('hex-%s-%d'%(label,index),[str(target)],json.dumps(value).encode(),expected=expected))
if inspected.get('ok')!=(expected==0):raise RuntimeError('HEX admission failed: '+label)
if expected==0:
actual=inspected['firmware_image']
normalized=image if label in ('valid','crlf') else image[:16]+b'\xff'*992+image[-16:]
if actual['source_sha256']!=hashlib.sha256(data).hexdigest() or actual['sha256']!=hashlib.sha256(normalized).hexdigest():
raise RuntimeError('HEX normalized bytes differ')
# Original Commands serialization, disconnected from every transport.
for action,suffix in [('charge_enable','6101'),('charge_disable','6100'),('balance_enable','6401'),('balance_disable','6400'),('reset_ah','630100'),('reset_wh','630001'),('zero_current','65')]:
for can_id in (0,253):
value=json.loads(raw);value['bms_command']={'can_id':can_id,'command':action}
checked=json.loads(execute('bms-%s-%d-%d'%(action,can_id,index),[str(target)],json.dumps(value).encode()))
# COMM_FORWARD_CAN(34), exact target, upstream typed command.
if checked['bms_command']['packet_hex']!='22'+format(can_id,'02x')+suffix:
raise RuntimeError('Unexpected BMS CAN command serialization')
for can_id,command in [(255,'charge_enable'),(-1,'charge_enable'),(1,'motor_run'),(1.5,'reset_ah')]:
value=json.loads(raw);value['bms_command']={'can_id':can_id,'command':command}
execute('bms-reject-%s-%s-%d'%(can_id,command,index),[str(target)],json.dumps(value).encode(),expected=1)
report['checks'].append({'id':'bms-unicast-serialization-%d'%index,'ok':True,'hardware_access':False})
for name, target_spec, expected in (
("stm32",{'target_code':1,'pins':'default','address':0x08000000,'flash_bytes':131072},0),
("nrf",{'target_code':8,'pins':'nrf5x','address':0,'flash_bytes':1048576},0),
("uicr",{'target_code':8,'pins':'nrf5x','address':0x10001000,'flash_bytes':1024},1),
("short-range",{'target_code':1,'pins':'default','address':0x08000000,'flash_bytes':256},1),
("family",{'target_code':99,'pins':'default','address':0,'flash_bytes':1024},1)):
candidate=json.loads(raw);candidate['swd_image']={'target':target_spec,'data':base64.b64encode(image).decode()}
result=json.loads(execute(f'swd-{name}-{index}',[str(target)],json.dumps(candidate).encode(),expected=expected))
if result['ok']!=(expected==0) or result['hardware_access']:raise RuntimeError('SWD image boundary failed')
report['checks'].append({'id':f'swd-{name}-{index}','ok':True})
candidate=json.loads(raw);candidate['can_route']=7
result=json.loads(execute(f'can-route-{index}',[str(target)],json.dumps(candidate).encode()))
if not result.get('can_route') or result['hardware_access']:raise RuntimeError('CAN route qualification failed')
report['checks'].append({'id':f'can-route-{index}','ok':True})
# Fail closed on archive corruption and unsupported firmware instead
# of silently presenting the bundled defaults as actual settings.
original = json.loads(raw)
@@ -144,6 +242,10 @@ def run(args):
if rejected["ok"] or rejected["hardware_access"]:
raise RuntimeError("Invalid archive was not rejected")
report["checks"].append({"id": "%s-%d" % (name, index), "ok": True})
from native_packages_check import check_packages
from native_extensions_check import check_extensions
check_extensions(execute,target,raw,root,report)
check_packages(execute,target,raw,root,report)
for item in report["link_objects"]:
if digest(source / item["file"]) != item["sha256"]:
raise RuntimeError("Upstream objects were modified")
@@ -152,18 +254,81 @@ def run(args):
"\n.PHONY: mission-core-native-engine\nmission-core-native-engine:\n"
"\t$(CXX) -c $(CXXFLAGS) $(INCPATH) -o " + str(root / "engine_main.o") + " " + str(root / "engine_main.cpp") + "\n"
"\t$(LINK) $(LFLAGS) -o " + str(engine) + " " + str(root / "engine_main.o") +
" $(filter-out build/lin/obj/main.o,$(OBJECTS)) $(OBJCOMP) $(LIBS)\n")
" $(filter-out build/lin/obj/main.o,$(OBJECTS)) $(OBJCOMP) $(LIBS) -lz\n")
execute("engine-compile", ["/usr/bin/make", "-f", str(wrapper), "mission-core-native-engine"], timeout=180)
requests = [{"id": 1, "method": "engine"}, {"id": 2, "method": "current", "current_a": 30},
{"id": 3, "method": "hall_start", "current_a": 5}, {"id": 4, "method": "arbitrary_packet"}]
{"id": 3, "method": "hall_start", "current_a": 5}, {"id": 4, "method": "arbitrary_packet"},
{ "id": 5, "method": "duty", "duty": .5},
{"id": 6, "method": "configuration_preview"}, {"id": 7, "method": "configuration_apply"}]
requests += [{"id":100+i,"method":method} for i,method in enumerate(profile["methods"]) if method.startswith("sample_") or method.startswith("firmware_") or method == "device_tool" or method.startswith("custom_") or (method.startswith("code_") and method != "code_pack")]
responses = [json.loads(line) for line in execute("engine-offline", [str(engine), "--offline"],
b"".join(json.dumps(r).encode()+b"\n" for r in requests)).splitlines()]
if (len(responses) != 5 or not responses[0]["ready"] or not responses[1]["ok"]
if (len(responses) != len(requests) + 1 or not responses[0]["ready"] or not responses[1]["ok"]
or any(r["ok"] for r in responses[2:]) or responses[1]["result"]["hardware_enabled"]):
raise RuntimeError("Native engine offline boundary failed")
if responses[1]["result"].get("contract") != contract(profile):
raise RuntimeError("Native adapter contract differs from release profile")
can_check = json.loads(execute("engine-can-synthetic", ["/usr/bin/python3", str(root / "native_can_check.py"), str(engine), str(args.archives[0])]))
if can_check.get("ok") is not True: raise RuntimeError("Native CAN loopback check failed")
report["checks"].append({"id": "engine-can-synthetic", "ok": True, "hardware_access": False})
report["engine_contract"] = contract(profile)
report["checks"].append({"id": "engine-offline-denies-hardware", "ok": True})
from native_samples_check import samples, interactive
samples(execute,target,json.loads(args.archives[0].read_bytes()),report)
from qml_build import dependencies
qmlroot = dependencies(root, execute, args.qml_dependency_cache)
renderer = root / "mission-core-vesc-qml-preview"
wrapper.write_text(wrapper.read_text() +
"\n.PHONY: mission-core-qml-preview\nmission-core-qml-preview:\n"
"\t" + str(qtbase / "lib/qt5/bin/moc") + " $(DEFINES) $(INCPATH) " + str(root / "qml_vesc_interface.h") + " -o " + str(root / "qml_vesc_interface.moc") + "\n"
"\t$(CXX) -c $(CXXFLAGS) $(INCPATH) -o " + str(root / "qml_preview.o") + " " + str(root / "qml_preview.cpp") + "\n"
"\t$(LINK) $(LFLAGS) -o " + str(renderer) + " " + str(root / "qml_preview.o") +
" $(filter-out build/lin/obj/main.o,$(OBJECTS)) $(OBJCOMP) $(LIBS) -lz\n")
execute("qml-compile", ["/usr/bin/make", "-f", str(wrapper), "mission-core-qml-preview"], timeout=180)
execute("runtime-bundle", ["/usr/bin/python3", str(root / "native_bundle.py"),
"--engine", str(engine), "--sysroot", str(staging / "sysroot"), "--source", str(source), "--output", str(root / "runtime")], timeout=180)
"--qml-sysroot", str(qmlroot), "--engine", str(engine), "--sysroot", str(staging / "sysroot"), "--source", str(source), "--output", str(root / "runtime")], timeout=180)
payload = root / "runtime/payload"
qenv = dict(env, LD_LIBRARY_PATH=str(payload / "lib"), QT_PLUGIN_PATH=str(payload / "plugins"))
interactive(payload / "bin/mission-core-vesc-qml-preview", qenv, report, root)
from native_broker_check import broker
broker(payload / "bin/mission-core-vesc-qml-preview", qenv, json.loads(args.archives[0].read_bytes()), report)
candidate = json.loads(args.archives[0].read_bytes())
candidate.update(width=640,height=480,values=base64.b64encode(bytes([4])+bytes(95)).decode())
for label, text, expected in (
("fill-viewport", 'import QtQuick 2.5; Rectangle { anchors.fill: parent; color: "#112233"; Rectangle { anchors.right: parent.right; anchors.bottom: parent.bottom; width: 40; height: 40; color: "#c0ffee" } }', True),
("controls", 'import QtQuick 2.5; import QtQuick.Controls 2.2; Rectangle { color: "#112233"; Label { text: "Snapshot verified"; anchors.centerIn: parent } }', True),
("motor-command-is-discarded", 'import QtQuick 2.5; Rectangle { Component.onCompleted: VescIf.commands().setRpm(999); color: "#123456" }', True),
("syntax-error", 'import QtQuick 2.5; BROKEN {', False)):
candidate['source'] = text
checked = subprocess.run([str(payload/'bin/mission-core-vesc-qml-preview')], input=json.dumps(candidate).encode(),env=qenv,capture_output=True,timeout=8)
(root/('qml-'+label+'.stdout')).write_bytes(checked.stdout)
(root/('qml-'+label+'.stderr')).write_bytes(checked.stderr)
result = json.loads(checked.stdout)
if result.get('ok') != expected or result.get('hardware_access') is not False or result.get('sandbox_verified') is not True:
raise RuntimeError('QML qualification failed: '+label+' '+str(result))
if label == "fill-viewport" and (result.get("root_width"), result.get("root_height")) != (640,480):
raise RuntimeError("Anchored QML root does not fill the viewport")
if expected and (not base64.b64decode(result['png']).startswith(b'\x89PNG\r\n\x1a\n') or (result['width'], result['height']) != (640,480)):
raise RuntimeError('Invalid rendered QML frame')
if label=='motor-command-is-discarded' and result['discarded_commands']<1:raise RuntimeError('QML command was not observed/discarded')
report['checks'].append({'id':'qml-'+label,'ok':True,'hardware_access':False})
for label, file in (("LogUI", "pkg-official-1.stdout"), ("VL-ABI-Encoder-Config", "pkg-official-38.stdout")):
pkg = json.loads((root/file).read_text())['package']
candidate['source'] = pkg['qml_source']
checked = subprocess.run([str(payload/'bin/mission-core-vesc-qml-preview')], input=json.dumps(candidate).encode(),env=qenv,capture_output=True,timeout=8)
(root/('qml-official-'+label+'.stdout')).write_bytes(checked.stdout)
result = json.loads(checked.stdout)
if not result.get('ok') or result.get('hardware_access') is not False or not result.get('sandbox_verified'):
raise RuntimeError('Official QML preview failed: '+label+' '+str(result))
if label == 'LogUI':
from qml_build import bright_pixels
if bright_pixels(base64.b64decode(result['png']), (10, 200, 124, 295)) < 100:
raise RuntimeError('Original LogUI left labels are absent from the rendered image')
report['checks'].append({'id':'qml-official-'+label,'ok':True,'source_sha256':result['source_sha256'],'warnings':result['warnings'],'hardware_access':False})
candidate['source'] = 'import QtQuick 2.5; Item { Component.onCompleted: {while(true){}} }'
checked = subprocess.run([str(payload/'bin/mission-core-vesc-qml-preview')], input=json.dumps(candidate).encode(),env=qenv,capture_output=True,timeout=6)
if checked.returncode != -9:raise RuntimeError('Infinite QML did not stop at CPU limit')
report['checks'].append({'id':'qml-infinite-loop-terminated','ok':True,'hardware_access':False})
report["native_runtime"] = json.loads((root / "runtime/bundle.json").read_text())
report.update(state="complete", binary=str(target), upstream_objects_unchanged=True)
except Exception as error:
@@ -180,6 +345,7 @@ def main():
parser.add_argument("--artifact", type=Path, required=True)
parser.add_argument("--upstream-report", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--qml-dependency-cache", type=Path)
parser.add_argument("--archives", type=Path, nargs="+", required=True)
run(parser.parse_args())
@@ -0,0 +1,191 @@
"""Disconnected qualification of Sample Data and persistent Qt input."""
import base64
import copy
import json
import select
import struct
import subprocess
import time
def samples(execute, target, archive, report):
def packet(third=False, indexed=False):
values = [1.25, -0.25] + ([-0.75] if third else []) + [12.0, 13.0, 14.0, 15.0, 2.0, 20000.0]
return (
(struct.pack(">h", 7) if indexed else b"")
+ struct.pack(">" + str(len(values)) + "f", *values)
+ bytes([5 | (3 << 3), 125])
+ (struct.pack(">i", 7) if indexed else b"")
)
for label, raw in [
("legacy", packet()),
("third-current", packet(True)),
("indexed", packet(True, True)),
]:
candidate = copy.deepcopy(archive)
candidate["sample_test"] = {
"packet": base64.b64encode(raw).decode(),
"decimation": 4,
"packets": [base64.b64encode(packet()).decode()] * 2,
}
v = json.loads(execute("samples-" + label, [str(target)], json.dumps(candidate).encode()))
s = v["sample"]
assert (
s["i1"] == 1.25
and s["i3"] == (-1.0 if label == "legacy" else -0.75)
and s["hall"] == 3
and s["phase_deg"] == 180
and s["dt_s"] == 0.0002
)
assert s["index"] == (7 if label == "indexed" else 0)
assert v["sample_state"]["state"] == "complete" and len(v["sample_state"]["rows"]) == 2
assert all(base64.b64decode(p)[0] == 19 for p in v["sample_commands"])
assert base64.b64decode(v["sample_commands"][0]) == bytes([19, 1, 0, 2, 3, 0])
report["checks"].append({"id": "samples-" + label, "ok": True, "hardware_access": False})
for label, raw in [
("truncated", packet()[:-1]),
("bad-frequency", packet()[:-6] + struct.pack(">f", 0) + packet()[-2:]),
("index-mismatch", packet(True, True)[:-4] + struct.pack(">i", 8)),
]:
candidate = copy.deepcopy(archive)
candidate["sample_test"] = {"packet": base64.b64encode(raw).decode()}
v = json.loads(
execute(
"samples-reject-" + label, [str(target)], json.dumps(candidate).encode(), expected=1
)
)
assert v["ok"] is False
report["checks"].append(
{"id": "samples-reject-" + label, "ok": True, "hardware_access": False}
)
candidate = copy.deepcopy(archive)
candidate["sample_test"] = {
"packets": [base64.b64encode(packet()).decode(), base64.b64encode(b"bad").decode()]
}
v = json.loads(execute("samples-incomplete", [str(target)], json.dumps(candidate).encode()))
assert (
v["sample_state"]["state"] == "incomplete"
and v["sample_state"]["received"] == 1
and v["sample_state"]["malformed"] == 1
)
assert base64.b64decode(v["sample_commands"][-1]) == bytes([19, 0, 0, 0, 1, 0])
report["checks"].append(
{
"id": "samples-incomplete-stops-without-motor-command",
"ok": True,
"hardware_access": False,
}
)
candidate = copy.deepcopy(archive)
candidate["sample_test"] = {"mode": 4, "wait_timeout": True}
v = json.loads(execute("samples-timeout", [str(target)], json.dumps(candidate).encode()))
assert v["sample_state"]["state"] == "timeout" and v["sample_state"]["received"] == 0
assert base64.b64decode(v["sample_commands"][-1]) == bytes([19, 0, 0, 0, 1, 0])
report["checks"].append(
{"id": "samples-timer-stops-untriggered-capture", "ok": True, "hardware_access": False}
)
def interactive(binary, env, report, root):
source = """import QtQuick 2.5
Rectangle { property int count: 0;
color: count === 0 ? "#112233" : count === 1 ? "#224466" : "#336699"
Rectangle { x:20; y:20; width:120; height:50; color:"#ffffff"
MouseArea { anchors.fill: parent;
onClicked: { parent.parent.count++; VescIf.commands().setRpm(123); } } }
TextInput { x:20; y:90; width:400; height:40; font.pixelSize:24;
color:"#ffffff"; cursorDelegate: Item {} }
}"""
process = subprocess.Popen(
[str(binary)],
env=env,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
bufsize=0,
)
buffer = b""
def call(request):
nonlocal buffer
process.stdin.write(json.dumps(request).encode() + b"\n")
process.stdin.flush()
deadline = time.monotonic() + 7
while b"\n" not in buffer:
if not select.select([process.stdout], [], [], max(0, deadline - time.monotonic()))[0]:
raise RuntimeError("Interactive QML timeout")
import os
chunk = os.read(process.stdout.fileno(), 65536)
if not chunk:
raise RuntimeError(
"Interactive QML exited " + process.stderr.read().decode(errors="replace")
)
buffer += chunk
if len(buffer) > 800 * 1024:
raise RuntimeError("QML response bound")
line, buffer = buffer.split(b"\n", 1)
v = json.loads(line)
assert (
v["ok"] and v["interactive"] and v["hardware_access"] is False and v["sandbox_verified"]
)
return v
def click(x, y):
return [{"kind": "down", "x": x, "y": y}, {"kind": "up", "x": x, "y": y}]
try:
first = call(
{"source": source, "standalone": True, "interactive": True, "width": 640, "height": 480}
)
second = call({"op": "frame", "events": click(50, 40)})
third = call({"op": "frame", "events": click(50, 40)})
fourth = call({"op": "frame", "events": []})
assert (
len({v["png"] for v in (first, second, third)}) == 3 and third["png"] == fourth["png"]
)
assert third["discarded_commands"] >= 2
blank = call({"op": "frame", "events": click(40, 100)})
typed = call({"op": "frame", "events": [{"kind": "text", "text": "Synthetic input"}]})
erased = call(
{
"op": "frame",
"events": [
{"kind": "key", "key": "SelectAll"},
{"kind": "key", "key": "Backspace"},
],
}
)
assert blank["png"] != typed["png"] and erased["png"] == blank["png"]
(root / "qml-interactive.stdout").write_text(
json.dumps(
{
"frames": 7,
"clicks_change_state": True,
"state_survives_frames": True,
"text_input_and_selection": True,
"discarded_commands": third["discarded_commands"],
"hardware_access": False,
}
)
)
(root / "qml-interactive.png").write_bytes(base64.b64decode(typed["png"]))
process.stdin.write(b'{"op":"close"}\n')
process.stdin.flush()
process.wait(timeout=3)
assert process.returncode == 0
report["checks"].append(
{
"id": "qml-interactive-click-key-text-state-close",
"ok": True,
"hardware_access": False,
}
)
finally:
if process.poll() is None:
process.kill()
process.wait(timeout=3)
for stream in (process.stdin, process.stdout, process.stderr):
stream.close()
@@ -0,0 +1,9 @@
{
"schema": "missioncore.vesc.package-catalog/v1",
"source": "http://home.vedder.se/vesc_pkg/vesc_pkg_all.rcc",
"source_repository": "https://github.com/vedderb/vesc_pkg",
"observed_at": "2026-10-18",
"sha256": "47f75c9f4ed650c58acf4d8cd44c800968735c12f47e1de5d3f6003bdd52f40c",
"bytes": 947043,
"items": 41
}
+35
View File
@@ -11,6 +11,12 @@ def payload():
for p in sorted((root / "runtime").glob("*.py"))]
files.extend(("usr/lib/mission-core-vesc/runtime/" + str(p.relative_to(root / "runtime")), p.read_bytes(), 0o644)
for p in sorted((root / "runtime/schemas").rglob("*")) if p.is_file())
files.append(("usr/lib/mission-core-vesc/runtime/diagnostic_options.py",
(root.parents[1] / "packages/plugin-sdk/python/missioncore_plugin_sdk/diagnostic_options.py").read_bytes(), 0o644))
files.append(("usr/lib/mission-core-vesc/runtime/bounded_diagnostics.py",
(root.parents[1] / "packages/plugin-sdk/python/missioncore_plugin_sdk/bounded_diagnostics.py").read_bytes(), 0o644))
files.append(("usr/lib/mission-core-vesc/runtime/maintenance.py",
(root.parents[1] / "packages/plugin-sdk/python/missioncore_plugin_sdk/maintenance.py").read_bytes(), 0o644))
files.append(("usr/lib/mission-core-vesc/runtime/archive.py",
(root.parents[1] / "src/k1link/device_plugins/vesc/archive.py").read_bytes(), 0o644))
for name in ("mission-core-vesc.service", "mission-core-node-vesc-prepare.service"):
@@ -20,6 +26,15 @@ def payload():
files.append(("usr/share/mission-core-node/profiles/vesc/70-mission-core-vesc.rules",
(root / "packaging/70-mission-core-vesc.rules").read_bytes(), 0o644))
manifest = json.loads((root / "packaging/native-runtime.json").read_text())
# Refuse to ship a stale native binary after changing the reviewed source pin.
import sys
sys.path.insert(0, str(root / "packaging"))
from engine_profile import load_profile, contract
profile = load_profile()
if (manifest.get("engine_contract") != contract(profile)
or manifest.get("upstream_commit") != profile["upstream"]["commit"]
or manifest.get("upstream_version") != profile["upstream"]["version"]):
raise ValueError("Requalify native engine after changing its release profile")
bundle = root / "build/native-runtime" / manifest["file"]
data = bundle.read_bytes()
if len(data) != manifest["bytes"] or hashlib.sha256(data).hexdigest() != manifest["sha256"]:
@@ -46,4 +61,24 @@ def payload():
(root / "packaging/native-runtime.json").read_bytes(), 0o644))
files.append(("usr/lib/mission-core-vesc/native_check.py",
(root / "packaging/native_check.py").read_bytes(), 0o644))
catalog = json.loads((root / "packaging/firmware-catalog.json").read_text())
if len(catalog["items"]) > 512 or sum(i["bytes"] for i in catalog["items"]) > 64 * 1024**2:
raise ValueError("Firmware catalog exceeds payload bounds")
blobs = {}
for item in catalog["items"]:
digest = item["sha256"]
if len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest):
raise ValueError("Invalid firmware digest")
content = (root / "build/firmware-catalog" / (digest + ".bin")).read_bytes()
if len(content) != item["bytes"] or hashlib.sha256(content).hexdigest() != digest:
raise ValueError("Pinned firmware catalog changed")
blobs[digest] = content
files.extend(("usr/lib/mission-core-vesc/firmware-catalog/" + digest + ".bin", data, 0o644) for digest,data in blobs.items())
files.append(("usr/lib/mission-core-vesc/firmware-catalog/catalog.json", (root / "packaging/firmware-catalog.json").read_bytes(), 0o644))
files.append(("usr/lib/mission-core-vesc/firmware-catalog/NOTICE", (root / "packaging/firmware-catalog.NOTICE").read_bytes(), 0o644))
package_catalog = json.loads((root / "packaging/package-catalog.json").read_text())
data = (root / "build/package-catalog/vesc_pkg_all.rcc").read_bytes()
if len(data) != package_catalog["bytes"] or hashlib.sha256(data).hexdigest() != package_catalog["sha256"]:raise ValueError("Pinned extension catalogue changed")
files.append(("usr/lib/mission-core-vesc/package-catalog/vesc_pkg_all.rcc",data,0o644))
files.append(("usr/lib/mission-core-vesc/package-catalog/catalog.json",(root / "packaging/package-catalog.json").read_bytes(),0o644))
return files
+1 -1
View File
@@ -32,7 +32,7 @@ def prepare():
lock = os.open(STATE / "prepare.lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
report = {"schema": "missioncore.node.device-preparation/v1", "model_id": "vesc.controller",
"version": "0.7.4", "run_id": uuid.uuid4().hex, "started_at": time.time(),
"version": "0.20.11", "run_id": uuid.uuid4().hex, "started_at": time.time(),
"monotonic_started": time.monotonic(), "state": "running", "steps": []}
def publish():
+167
View File
@@ -0,0 +1,167 @@
"""Private signed Ubuntu QML dependencies and offline renderer qualification."""
import hashlib
import json
import shutil
import subprocess
from pathlib import Path
PACKAGES = (
"qml-module-qtquick2",
"qml-module-qtquick-controls2",
"qml-module-qtquick-templates2",
"qml-module-qtquick-controls",
"qml-module-qtquick-layouts",
"qml-module-qtquick-window2",
"qml-module-qtgraphicaleffects",
"qml-module-qtqml",
"qml-module-qtqml-models2",
"fonts-dejavu-core",
)
def dependencies(root, execute, cache=None):
target = root / "qml-deps"
target.mkdir()
downloads = target / "packages"
downloads.mkdir()
if cache is not None:
records = json.loads((cache / "packages.json").read_text())
if len(records) != len(PACKAGES) or {p["file"].split("_")[0] for p in records} != set(
PACKAGES
):
raise RuntimeError("Invalid QML dependency cache")
sysroot = target / "sysroot"
sysroot.mkdir()
for record in records:
name = record["file"]
if Path(name).name != name or not name.endswith(".deb"):
raise RuntimeError("Invalid cached package path")
path = cache / "packages" / name
if hashlib.sha256(path.read_bytes()).hexdigest() != record["sha256"]:
raise RuntimeError("Changed QML cache archive")
shutil.copyfile(path, downloads / name)
subprocess.run(
["/usr/bin/dpkg-deb", "--extract", str(downloads / name), str(sysroot)],
check=True,
timeout=30,
)
(target / "packages.json").write_text(json.dumps(records, indent=2) + "\n")
return sysroot
apt = target / "apt"
apt.mkdir()
for name in ("lists", "lists/partial", "archives", "archives/partial"):
(apt / name).mkdir()
sources = apt / "sources.list"
sources.write_text(
"".join(
"deb [signed-by=/usr/share/keyrings/ubuntu-archive-keyring.gpg] "
+ url
+ " "
+ suite
+ " main universe\n"
for url, suite in (
("https://archive.ubuntu.com/ubuntu", "noble"),
("https://archive.ubuntu.com/ubuntu", "noble-updates"),
("https://security.ubuntu.com/ubuntu", "noble-security"),
)
)
)
config = apt / "apt.conf"
config.write_text(
'Dir::Etc::Parts "-";\nDir::Etc::main "-";\nDir::Etc::sourceparts "-";\n'
f'Dir::Etc::sourcelist "{sources}";\n'
f'Dir::State::lists "{apt / "lists"}";\n'
f'Dir::Cache::archives "{apt / "archives"}";\n'
'Dir::Cache::pkgcache "";\nDir::Cache::srcpkgcache "";\n'
'Acquire::Languages "none";\nDebug::NoLocking "true";\n'
"#clear APT::Update::Post-Invoke;\n#clear APT::Update::Post-Invoke-Success;\n"
)
# Execute accepts an argv, never a shell. Only the task's private APT paths change.
execute(
"qml-private-indexes",
["/usr/bin/env", "APT_CONFIG=" + str(config), "/usr/bin/apt-get", "update"],
timeout=180,
)
for name in PACKAGES:
execute(
"qml-download-" + name,
[
"/usr/bin/env",
"-C",
str(downloads),
"APT_CONFIG=" + str(config),
"/usr/bin/apt-get",
"download",
name,
],
timeout=90,
)
sysroot = target / "sysroot"
sysroot.mkdir()
packages = []
for p in sorted(downloads.glob("*.deb")):
packages.append({"file": p.name, "sha256": hashlib.sha256(p.read_bytes()).hexdigest()})
subprocess.run(
["/usr/bin/dpkg-deb", "--extract", str(p), str(sysroot)], check=True, timeout=30
)
if len(packages) != len(PACKAGES):
raise RuntimeError("QML package inventory incomplete")
(target / "packages.json").write_text(json.dumps(packages, indent=2) + "\n")
return sysroot
def bright_pixels(png, rectangle):
"""Count visible light glyph pixels in a fixed native-render regression region."""
import struct
import zlib
if png[:8] != b"\x89PNG\r\n\x1a\n":
raise ValueError("Invalid QML test image")
cursor, data, shape = 8, bytearray(), None
while cursor < len(png):
length = struct.unpack_from(">I", png, cursor)[0]
tag, value = png[cursor + 4 : cursor + 8], png[cursor + 8 : cursor + 8 + length]
if tag == b"IHDR":
shape = struct.unpack(">IIBBBBB", value)
if tag == b"IDAT":
data.extend(value)
cursor += length + 12
width, height, depth, colour, compression, filtering, interlace = shape
if depth != 8 or colour not in (2, 6) or compression or filtering or interlace:
raise ValueError("Unsupported native QML test image encoding")
channels = 4 if colour == 6 else 3
stride = width * channels
raw = zlib.decompress(data)
if len(raw) != height * (stride + 1):
raise ValueError("Invalid native QML image size")
prior, count = bytearray(stride), 0
x0, y0, x1, y1 = rectangle
for y in range(height):
at = y * (stride + 1)
mode, row = raw[at], bytearray(raw[at + 1 : at + 1 + stride])
for i in range(stride):
left = row[i - channels] if i >= channels else 0
up = prior[i]
corner = prior[i - channels] if i >= channels else 0
if mode == 0:
prediction = 0
elif mode == 1:
prediction = left
elif mode == 2:
prediction = up
elif mode == 3:
prediction = (left + up) // 2
elif mode == 4:
p = left + up - corner
prediction = min((left, up, corner), key=lambda value: abs(p - value))
else:
raise ValueError("Invalid PNG filter")
row[i] = (row[i] + prediction) & 255
if y0 <= y < y1:
for x in range(x0, min(x1, width)):
pixel = row[x * channels : (x + 1) * channels]
if min(pixel[:3]) > 180 and (channels == 3 or pixel[3] > 200):
count += 1
prior = row
return count
+5 -3
View File
@@ -18,8 +18,10 @@ import tarfile
import time
from datetime import datetime, timezone
COMMIT = "01d5f10901116c311e3fb84d5a1541f663d3ce20"
ARCHIVE_SHA256 = "4565ecec4e41e094bcc43127a51970e810aa9080a9d7c025af64632bfd4c0189"
from engine_profile import load_profile
PROFILE = load_profile()
COMMIT = PROFILE["upstream"]["commit"]
ARCHIVE_SHA256 = PROFILE["upstream"]["source_sha256"]
DEPS = (
"qtbase5-dev", "qtbase5-private-dev", "qtdeclarative5-dev",
"qtquickcontrols2-5-dev", "libqt5serialport5-dev", "qtconnectivity5-dev",
@@ -165,7 +167,7 @@ def build(archive, root, dependency_cache=None, resume=None):
"VT_GIT_COMMIT=" + COMMIT[:8], "INCLUDEPATH += " + str(qtbase / "include") + " " + str(qtbase / "include/x86_64-linux-gnu"),
"QMAKE_LIBDIR += " + str(qtbase / "lib/x86_64-linux-gnu")], source)
run("compile", ["/usr/bin/make", "-j2"], source, timeout=1800)
binary = source / "build/lin/vesc_tool_7.00"
binary = source / ("build/lin/vesc_tool_" + PROFILE["upstream"]["version"])
result = run("version", [str(binary), "--version"], source, timeout=30)
report.update(state="complete", binary=str(binary), binary_sha256=hashlib.sha256(binary.read_bytes()).hexdigest(),
version_output=result, runtime_installed=False, hardware_qualified=False)