feat(bms): discover JK batteries and integrate read-only telemetry scenes
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-BUS Bus Configuration 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<policy user="mission-core-jk-bms">
|
||||
<allow send_destination="org.bluez" send_interface="org.freedesktop.DBus.ObjectManager" send_member="GetManagedObjects"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.freedesktop.DBus.Properties" send_member="GetAll"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.freedesktop.DBus.Properties" send_member="Set"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.Adapter1" send_member="SetDiscoveryFilter"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.Adapter1" send_member="StartDiscovery"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.Adapter1" send_member="StopDiscovery"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.Device1" send_member="Connect"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.Device1" send_member="Disconnect"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.GattCharacteristic1" send_member="StartNotify"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.GattCharacteristic1" send_member="StopNotify"/>
|
||||
<allow send_destination="org.bluez" send_interface="org.bluez.GattCharacteristic1" send_member="WriteValue"/>
|
||||
<allow receive_sender="org.bluez"/>
|
||||
</policy>
|
||||
</busconfig>
|
||||
@@ -0,0 +1,40 @@
|
||||
[Unit]
|
||||
Description=Mission Core JK BMS read-only Bluetooth observer
|
||||
After=bluetooth.service
|
||||
Wants=bluetooth.service
|
||||
StartLimitIntervalSec=120
|
||||
StartLimitBurst=5
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=mission-core-jk-bms
|
||||
Group=mission-core-node
|
||||
WorkingDirectory=/usr/lib/mission-core-jk-bms
|
||||
ExecStart=/usr/bin/python3 -B -m runtime.server
|
||||
RuntimeDirectory=mission-core-jk-bms
|
||||
RuntimeDirectoryMode=0750
|
||||
StateDirectory=mission-core-jk-bms
|
||||
StateDirectoryMode=0700
|
||||
UMask=0007
|
||||
Restart=on-failure
|
||||
RestartSec=15
|
||||
TimeoutStopSec=20
|
||||
NoNewPrivileges=yes
|
||||
CapabilityBoundingSet=
|
||||
AmbientCapabilities=
|
||||
PrivateNetwork=yes
|
||||
PrivateDevices=yes
|
||||
ProtectSystem=strict
|
||||
ProtectHome=yes
|
||||
ProtectKernelTunables=yes
|
||||
ProtectKernelModules=yes
|
||||
ProtectControlGroups=yes
|
||||
RestrictSUIDSGID=yes
|
||||
RestrictAddressFamilies=AF_UNIX
|
||||
MemoryMax=96M
|
||||
TasksMax=16
|
||||
LogRateLimitIntervalSec=30s
|
||||
LogRateLimitBurst=10
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Versioned BMS runtime and access policy shipped by the Node installer."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def payload():
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
result = [
|
||||
("usr/lib/mission-core-jk-bms/runtime/" + p.name, p.read_bytes(), 0o644)
|
||||
for p in sorted((root / "runtime").glob("*.py"))
|
||||
]
|
||||
for name, target in [
|
||||
("mission-core-jk-bms.service", "usr/lib/systemd/system/"),
|
||||
("mission-core-jk-bms.conf", "usr/share/dbus-1/system.d/"),
|
||||
]:
|
||||
result.append((target + name, (root / "packaging" / name).read_bytes(), 0o644))
|
||||
return result
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Bounded prepared-Ubuntu package smoke check; never installs or opens hardware."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import subprocess
|
||||
import tempfile
|
||||
import time
|
||||
import uuid
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def qualify(package, expected):
|
||||
assert os.geteuid() != 0
|
||||
release = platform.freedesktop_os_release()
|
||||
assert (release["ID"], release["VERSION_ID"], platform.machine()) == (
|
||||
"ubuntu",
|
||||
"24.04",
|
||||
"x86_64",
|
||||
)
|
||||
raw = package.read_bytes()
|
||||
assert hashlib.sha256(raw).hexdigest() == expected
|
||||
report = dict(
|
||||
schema="missioncore.bms.prepared-host-package-check/v1",
|
||||
session_id=uuid.uuid4().hex,
|
||||
started_at=datetime.now(UTC).isoformat(),
|
||||
monotonic_started=time.monotonic(),
|
||||
clean_image_qualified=False,
|
||||
hardware_access=False,
|
||||
checks=[],
|
||||
)
|
||||
|
||||
def run(name, args, allowed=(0,), **kwargs):
|
||||
result = subprocess.run(args, capture_output=True, timeout=60, **kwargs)
|
||||
assert result.returncode in allowed, name + ": " + result.stderr.decode()[:300]
|
||||
report["checks"].append(dict(id=name, exit_code=result.returncode))
|
||||
return result.stdout
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="bms-package-", dir=package.parent) as scratch:
|
||||
root = Path(scratch)
|
||||
run("control", ["dpkg-deb", "-e", str(package), str(root / "control")])
|
||||
run("payload", ["dpkg-deb", "-x", str(package), str(root / "payload")])
|
||||
for name in ["postinst", "prerm"]:
|
||||
run("shell-" + name, ["/bin/sh", "-n", str(root / "control" / name)])
|
||||
control = (root / "control/control").read_text()
|
||||
assert "python3-dbus" in control and "bluez (>= 5.72)" in control
|
||||
runtime = root / "payload/usr/lib/mission-core-jk-bms"
|
||||
for path in runtime.rglob("*.py"):
|
||||
compile(path.read_text(), str(path), "exec")
|
||||
run(
|
||||
"python-imports",
|
||||
[
|
||||
"/usr/bin/python3",
|
||||
"-B",
|
||||
"-c",
|
||||
"import runtime.protocol, runtime.service, runtime.bluez, runtime.server; "
|
||||
"from gi.repository import GLib",
|
||||
],
|
||||
cwd=runtime,
|
||||
)
|
||||
help_text = run(
|
||||
"node-executable-help",
|
||||
[str(root / "payload/usr/lib/mission-core-node/node-agent"), "--help"],
|
||||
allowed=(0, 1, 2),
|
||||
)
|
||||
assert len(help_text) < 65536
|
||||
run("apt-simulation", ["apt-get", "--simulate", "--no-remove", "install", str(package)])
|
||||
report.update(
|
||||
state="complete",
|
||||
finished_at=datetime.now(UTC).isoformat(),
|
||||
duration_seconds=time.monotonic() - report["monotonic_started"],
|
||||
package_sha256=expected,
|
||||
)
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("package", type=Path)
|
||||
parser.add_argument("sha256")
|
||||
args = parser.parse_args()
|
||||
qualify(args.package.resolve(), args.sha256)
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Add BMS to the pinned installed Node110 release, retaining other SDK payloads.
|
||||
|
||||
The new Node binary embeds the rebuilt shared local UI. Full future builds use
|
||||
build_deb.py; this incremental delivery preserves every unrelated installed
|
||||
runtime and installer member instead of downgrading to the source baseline.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import runpy
|
||||
import sys
|
||||
import tarfile
|
||||
from pathlib import Path
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
NODE = REPO / "apps/node-agent"
|
||||
BASE_SHA = "573280f338c833ff7cf00592d9bfb4ee292bf685fd788bae47ac5806524a497e"
|
||||
VERSION = "0.8.53-111"
|
||||
sys.path.insert(0, str(REPO / "scripts/packaging"))
|
||||
from debian import package # noqa: E402
|
||||
|
||||
|
||||
def build(binary, output):
|
||||
if output.exists():
|
||||
raise FileExistsError("Published releases are immutable")
|
||||
base = NODE / "build/link-feedback-110/mission-core-node_0.8.53-110_amd64.deb"
|
||||
raw = base.read_bytes()
|
||||
if hashlib.sha256(raw).hexdigest() != BASE_SHA:
|
||||
raise ValueError("Qualified baseline changed")
|
||||
source = io.BytesIO(raw)
|
||||
assert source.read(8) == b"!<arch>\n"
|
||||
archives = {}
|
||||
while header := source.read(60):
|
||||
size = int(header[48:58])
|
||||
name = header[:16].decode().strip().rstrip("/")
|
||||
archives[name] = source.read(size)
|
||||
if size % 2:
|
||||
source.read(1)
|
||||
|
||||
def members(name):
|
||||
with tarfile.open(fileobj=io.BytesIO(archives[name]), mode="r:gz") as archive:
|
||||
return [(m.name, archive.extractfile(m).read(), m.mode) for m in archive if m.isfile()]
|
||||
|
||||
controls, files = members("control.tar.gz"), members("data.tar.gz")
|
||||
old = {name: data for name, data, _ in files}
|
||||
control = dict((n, d) for n, d, _ in controls)["control"]
|
||||
assert b"Version: 0.8.53-110\n" in control
|
||||
control = control.replace(b"Version: 0.8.53-110\n", f"Version: {VERSION}\n".encode())
|
||||
control = control.replace(b"Depends: ", b"Depends: python3-dbus, bluez (>= 5.72), ", 1)
|
||||
patched = {"control": control}
|
||||
for name, data, _ in controls:
|
||||
if name == "postinst":
|
||||
needle = b" # Only bootstrap required"
|
||||
assert needle in data
|
||||
data = data.replace(
|
||||
needle,
|
||||
b' if ! getent passwd mission-core-jk-bms >/dev/null; then\n addu'
|
||||
b'ser --system --group --home /var/lib/mission-core-jk-bms --no-create-h'
|
||||
b'ome --disabled-login mission-core-jk-bms\n fi\n'
|
||||
+ needle,
|
||||
1,
|
||||
)
|
||||
data = data.replace(
|
||||
b" systemctl daemon-reload",
|
||||
b' systemctl daemon-reload\n systemctl reload dbus.service\n '
|
||||
b' systemctl enable mission-core-jk-bms.service\n systemctl restart'
|
||||
b' mission-core-jk-bms.service',
|
||||
1,
|
||||
)
|
||||
patched[name] = data
|
||||
if name == "prerm":
|
||||
needle = b'case "$1" in\n upgrade|remove|deconfigure)'
|
||||
assert needle in data
|
||||
patched[name] = data.replace(
|
||||
needle,
|
||||
needle
|
||||
+ (b"\n if [ -d /run/systemd/system ] && "
|
||||
b"[ -f /usr/lib/systemd/system/mission-core-jk-bms.service ]; then\n"
|
||||
b" systemctl disable --now mission-core-jk-bms.service\n fi"),
|
||||
1,
|
||||
)
|
||||
compiled = binary.read_bytes()
|
||||
assert compiled[:6] == b"\x7fELF\x02\x01" and compiled[18:20] == b"\x3e\x00"
|
||||
sources = [
|
||||
p
|
||||
for root in [
|
||||
REPO / "plugins/jk-bms",
|
||||
NODE / "internal",
|
||||
NODE / "cmd",
|
||||
NODE / "ui/src",
|
||||
REPO / "packages/sensor-ui/src",
|
||||
]
|
||||
for p in root.rglob("*")
|
||||
if p.is_file() and "__pycache__" not in p.parts
|
||||
]
|
||||
provenance = {
|
||||
"schema": "missioncore.node.packaging-revision/v1",
|
||||
"version": VERSION,
|
||||
"qualified_base_sha256": BASE_SHA,
|
||||
"qualified_base_provenance": json.loads(
|
||||
old["usr/share/doc/mission-core-node/provenance.json"]
|
||||
),
|
||||
"scope": "Read-only JK BLE discovery and bounded telemetry in the Node equipment view",
|
||||
"binary_sha256": hashlib.sha256(compiled).hexdigest(),
|
||||
"source_files": {
|
||||
str(p.relative_to(REPO)): hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
for p in sorted(sources)
|
||||
},
|
||||
}
|
||||
changes = {
|
||||
"usr/lib/mission-core-node/node-agent": compiled,
|
||||
"usr/share/doc/mission-core-node/provenance.json": (
|
||||
json.dumps(provenance, indent=2) + "\n"
|
||||
).encode(),
|
||||
}
|
||||
added = runpy.run_path(str(Path(__file__).with_name("payload.py")))["payload"]()
|
||||
assert not any(name in old for name, _, _ in added)
|
||||
controls = [(name, patched.get(name, data), mode) for name, data, mode in controls]
|
||||
files = [(name, changes.get(name, data), mode) for name, data, mode in files] + added
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_bytes(package(controls, files))
|
||||
report = {
|
||||
"version": VERSION,
|
||||
"base_sha256": BASE_SHA,
|
||||
"sha256": hashlib.sha256(output.read_bytes()).hexdigest(),
|
||||
"bytes": output.stat().st_size,
|
||||
"changed_controls": list(patched),
|
||||
"changed_payloads": list(changes),
|
||||
"added_payloads": [n for n, _, _ in added],
|
||||
}
|
||||
output.with_suffix(".json").write_text(json.dumps(report, indent=2) + "\n")
|
||||
print(json.dumps(report))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--binary", required=True, type=Path)
|
||||
parser.add_argument("--output", required=True, type=Path)
|
||||
args = parser.parse_args()
|
||||
build(args.binary, args.output)
|
||||
Reference in New Issue
Block a user