App > Put with Files: restore a backup zip onto the connected device

Follows Ontrol's Workbench tool (BPutWithFilesTool / PutApp): the backup's
app.sax is encoded for the device's kits and put as app.sab.writing, renamed
to app.sab.stage; the platform service's deleteFile clears fonts/* and
images/*, then images, fonts (from Sedona home's bank, in the device's cut)
and the boot logo go. The zip is checked against the device first: same
platform (Orion, Rion or P-ION, from the platform id), and kits the device
can load. Falls back to the backup's app.sab, with its kits.scode if needed.

- sab_app.encode_sax: .sax -> .sab, ported from Py_sab2sax with Java's value
  parsing (fromLiteral, nullbool/nullfloat, Integer.decode); byte-identical
  to sedonac on the saved backups
- app_backup.native_image: port of OntOxImageUtil's png -> native .bin
- sox.put_file / rename_file
- Get with Files: Orion's boot logo is system/logo.jpg
- A restart that goes unanswered is taken as the device going down

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-10 23:37:45 +03:00
co-authored by Claude Opus 5.5
parent 1deb31f3b3
commit 232eea99f4
5 changed files with 932 additions and 41 deletions
+214 -1
View File
@@ -1,4 +1,5 @@
"""Reads a device's app.sab and writes it back out as app.sax.
"""Reads a device's app.sab and writes it back out as app.sax, and encodes an app.sax
into app.sab (encode_sax).
Ported from Py_sab2sax (sax.py/sab.py), itself a port of sedona.offline.OfflineApp
(decodeAppBinary + encodeAppXml); its output matches `sedonac app.sab` byte for byte,
@@ -408,3 +409,215 @@ def _path_of(c):
parts.append(c["name"])
c = c["parent"]
return "/" + "/".join(reversed(parts)) if parts else "/"
# --- encoding app.sax to app.sab ------------------------------------------------------
#
# Ported from Py_sab2sax's sab.py (sedona.offline.OfflineApp decodeAppXml +
# encodeAppBinary), with the value parsing brought in line with the Java Value classes:
# asStr text is unescaped as TextUtil.fromLiteral does, "nullbool"/"nullfloat" are
# read, and integers take Integer.decode's '#' hex and leading-zero octal.
def _decode_int(raw):
"""Integer.decode."""
if raw in (None, "", "null"):
return 0
s = raw.strip()
neg = s.startswith("-")
if s[:1] in "+-":
s = s[1:]
if s[:2].lower() == "0x":
v = int(s[2:], 16)
elif s.startswith("#"):
v = int(s[1:], 16)
elif len(s) > 1 and s.startswith("0"):
v = int(s[1:], 8)
else:
v = int(s)
return -v if neg else v
def _from_literal(s):
"""TextUtil.fromLiteral."""
if "\\" not in s:
return s
escapes = {"0": "\0", "n": "\n", "r": "\r", "t": "\t", "\\": "\\", '"': '"', "$": "$"}
out, i = [], 0
while i < len(s):
c = s[i]
if c == "\\":
i += 1
if i >= len(s) or s[i] not in escapes:
raise SabError(f"unknown escape sequence in {s!r}")
c = escapes[s[i]]
out.append(c)
i += 1
return "".join(out)
class _Writer:
def __init__(self):
self.b = bytearray()
def u1(self, v): self.b.append(v & 0xFF)
def u2(self, v): self.b += struct.pack(">H", v & 0xFFFF)
def i4(self, v): self.b += struct.pack(">i", ((v + 2**31) % 2**32) - 2**31)
def i8(self, v): self.b += struct.pack(">q", v)
def f4(self, v): self.b += struct.pack(">f", _to_f32(v))
def f8(self, v): self.b += struct.pack(">d", v)
def str_(self, s):
self.b += s.encode("ascii")
self.u1(0)
def _encode_value(out, slot, raw):
"""One config prop, from its sax text (or the manifest default when absent)."""
vtype, flags = slot.type, slot.flags
if "s" in flags: # asStr Buf: u2 len (incl NUL)
data = _from_literal(raw or "").encode("ascii")
out.u2(len(data) + 1)
out.b += data
out.u1(0)
elif vtype == "bool":
if raw in ("null", "nullbool"):
out.u1(2)
elif raw in (None, "", "false", "true"):
out.u1(1 if raw == "true" else 0)
else:
raise SabError(f"invalid bool {raw!r}")
elif vtype == "byte":
out.u1(_decode_int(raw))
elif vtype == "short":
out.u2(_decode_int(raw))
elif vtype == "int":
out.i4(_decode_int(raw))
elif vtype == "long":
out.i8(_decode_int(raw))
elif vtype in ("float", "double"):
v = float("nan") if raw in ("null", "nullfloat", "nulldouble") else _flt(raw)
(out.f4 if vtype == "float" else out.f8)(v)
elif vtype in ("sys::Buf", "buf"):
data = base64.b64decode(raw) if raw else b""
out.u2(len(data))
out.b += data
else:
raise SabError(f"unhandled slot type {vtype}")
def encode_sax(sax, checksums=None):
"""app.sax (text or bytes) -> app.sab bytes, as `sedonac app.sax` writes it.
checksums, {kit name: checksum hex}, stands in for the sax's own -- how an app goes
to a device whose kits are other builds than the ones it was saved with. Every
kit's manifest must be in Sedona home under the checksum used.
"""
root = ET.fromstring(sax)
schema_elem, app_elem = root.find("schema"), root.find("app")
if schema_elem is None or app_elem is None:
raise SabError("not a Sedona app: no <schema> or <app>")
parts = []
for k in schema_elem.findall("kit"):
name = k.get("name")
cks = (checksums or {}).get(name) or k.get("checksum")
if not cks:
raise SabError(f"no checksum for kit '{name}'")
parts.append((name, f"{int(cks, 16):08x}"))
parts.sort(key=lambda p: ("" if p[0] == "sys" else "\x01" + p[0])) # sortKits
for name, cks in parts:
path = schema.find_manifest_path(name, cks)
if path is None or not path.endswith(f"-{cks}.xml"):
raise SabError(f"no manifest for kit '{name}' {cks} in Sedona home")
kits, types_by_q = _load_kits(parts)
type_ids = {}
for ki, ((kname, _), tlist) in enumerate(zip(parts, kits)):
for t in tlist:
type_ids[f"{kname}::{t.get('name')}"] = (ki, int(t.get("id")))
cache = {}
comps = []
def walk(elem, qtype, parent):
if qtype not in type_ids:
raise SabError(f"unknown type '{qtype}' ({elem.get('name')})")
c = {"elem": elem, "type": qtype, "parent": parent, "kids": [],
"id": int(elem.get("id")) if elem.get("id") else None}
comps.append(c)
if parent is not None:
parent["kids"].append(c)
for kid in elem.findall("comp"):
walk(kid, kid.get("type"), c)
return c
app = walk(app_elem, "sys::App", None)
app["id"] = 0
used = {c["id"] for c in comps if c["id"] is not None}
next_id = 1
for c in comps: # ids for comps the sax gives none
if c["id"] is None:
while next_id in used:
next_id += 1
c["id"] = next_id
used.add(next_id)
by_id = {}
for c in comps:
if c["id"] in by_id:
raise SabError(f"duplicate id: {c['id']}")
by_id[c["id"]] = c
out = _Writer()
out.i4(0x73617070) # "sapp"
out.i4(0x0003) # version 0.3
out.u1(len(parts))
for name, cks in parts:
out.str_(name)
out.i4(int(cks, 16))
out.u2(max(by_id))
for cid in sorted(by_id):
c = by_id[cid]
ki, ti = type_ids[c["type"]]
out.u2(cid)
out.u1(ki)
out.u1(ti)
out.str_(c["elem"].get("name", "app") if cid else "app")
out.u2(c["parent"]["id"] if c["parent"] else 0xFFFF)
out.u2(c["kids"][0]["id"] if c["kids"] else 0xFFFF)
sibling = 0xFFFF
if c["parent"]:
kids = c["parent"]["kids"]
i = kids.index(c)
if i + 1 < len(kids):
sibling = kids[i + 1]["id"]
out.u2(sibling)
props = {p.get("name"): p.get("val") for p in c["elem"].findall("prop")}
for slot in _resolve_slots(c["type"], types_by_q, cache):
if "a" in slot.flags or "c" not in slot.flags:
continue # config props only
_encode_value(out, slot, props.get(slot.name, slot.default))
out.u1(ord(";"))
out.u2(0xFFFF)
def ref(text):
path, slot_name = text.rsplit(".", 1)
cur = app
for part in (p for p in path.split("/") if p):
cur = next((k for k in cur["kids"] if k["elem"].get("name") == part), None)
if cur is None:
raise SabError(f"link to a missing component: {text}")
names = [s.name for s in _resolve_slots(cur["type"], types_by_q, cache)]
if slot_name not in names:
raise SabError(f"link to a missing slot: {text}")
return cur["id"], names.index(slot_name)
links = root.find("links")
for link in (links.findall("link") if links is not None else ()):
fc, fs = ref(link.get("from"))
tc, ts = ref(link.get("to"))
out.u2(fc)
out.u1(fs)
out.u2(tc)
out.u1(ts)
out.u2(0xFFFF)
out.u1(ord("."))
return bytes(out.b)