Files
NODEDC_MISSION_CORE/src/k1link/fleet/board_layout.py
T

46 lines
1.9 KiB
Python

"""Operator presentation only; never transported to a motor controller."""
import hashlib
import json
from pathlib import Path
from .trust import atomic_private
SCHEMA = "missioncore.board-layout/v1"
SECTIONS = ("computer", "settings", "devices")
def path(root: Path, vehicle: str) -> Path:
return root / "board-layouts" / (hashlib.sha256(vehicle.encode()).hexdigest() + ".json")
def read(root: Path, vehicle: str) -> dict:
target = path(root, vehicle)
if not target.exists():
return {"schema": SCHEMA, "revision": 0, "open_sections": list(SECTIONS)}
if target.is_symlink() or target.stat().st_size > 4096:
raise ValueError("Invalid layout file")
value = json.loads(target.read_bytes())
if (not isinstance(value, dict) or set(value) != {"schema", "revision", "open_sections"}
or value["schema"] != SCHEMA or type(value["revision"]) is not int
or not 0 <= value["revision"] < 2**53-1
or not isinstance(value["open_sections"], list)
or any(item not in SECTIONS for item in value["open_sections"])
or len(set(value["open_sections"])) != len(value["open_sections"])):
raise ValueError("Invalid layout document")
return value
def update(root: Path, vehicle: str, section: str, opened: bool) -> dict:
# Caller holds the fleet writer lock. A patch cannot lose another section.
if section not in SECTIONS or type(opened) is not bool:
raise ValueError("Invalid layout change")
value = read(root, vehicle)
opened_sections = set(value["open_sections"])
if opened:
opened_sections.add(section)
else:
opened_sections.discard(section)
value.update(revision=value["revision"]+1, open_sections=[s for s in SECTIONS if s in opened_sections])
atomic_private(path(root, vehicle), (json.dumps(value, indent=2)+"\n").encode())
return value