openhmi-nx: decode, encode, render Nextion HMI projects; .tft research
Black-box reverse-engineered .HMI format (container, three checksums, pages, all 31 component types, pictures, fonts), readable JSON, page renderer matching Nextion Editor, demo project built from code and a test suite (66 tests). See docs/COVERAGE.md for status. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
69e22cfb06
70 files changed
+25058
No files matched your search
@@ -0,0 +1,7 @@
|
||||
"""nxhmi -- read, verify and write Nextion Editor .HMI project files without the Editor."""
|
||||
from .checksum import page_crc, main_crc, table_crc
|
||||
from .container import HMIFile, build
|
||||
from .page import Page, Component, Attr, Group
|
||||
|
||||
__version__ = "0.1.0"
|
||||
__all__ = ["page_crc", "main_crc", "table_crc", "HMIFile", "build", "Page", "Component", "Attr", "Group"]
|
||||
@@ -0,0 +1,5 @@
|
||||
import sys
|
||||
|
||||
from .cli import main
|
||||
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Checksums used inside Nextion Editor .HMI project files.
|
||||
|
||||
All three are CRC-32 with polynomial 0x04C11DB7, processed MSB-first (no bit reflection),
|
||||
initial value 0xFFFFFFFF and no final XOR -- i.e. the algorithm of the STM32 hardware CRC unit.
|
||||
They differ only in how the input is fed:
|
||||
|
||||
* ``word_per_byte_crc`` -- every input *byte* is zero-extended and fed as one 32-bit word.
|
||||
Used for pages (``*.pa``) and the project header (``main.HMI``), each followed by a
|
||||
10-byte "tail" (see :func:`page_crc` / :func:`main_crc`).
|
||||
* ``dword_crc`` -- input is read as little-endian 32-bit words. Used for the file table,
|
||||
followed by the constant word 0x43454441 (ASCII "ADEC").
|
||||
|
||||
These were reverse-engineered black-box (by editing projects in the Editor and comparing
|
||||
saved files); see docs/FORMAT.md for the evidence.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
|
||||
POLY = 0x04C11DB7
|
||||
INIT = 0xFFFFFFFF
|
||||
TABLE_MAGIC = 0x43454441 # "ADEC"
|
||||
|
||||
_TABLE = []
|
||||
for _i in range(256):
|
||||
_c = _i << 24
|
||||
for _ in range(8):
|
||||
_c = ((_c << 1) ^ POLY) & 0xFFFFFFFF if _c & 0x80000000 else (_c << 1) & 0xFFFFFFFF
|
||||
_TABLE.append(_c)
|
||||
|
||||
|
||||
def _feed_byte(c: int, b: int) -> int:
|
||||
return ((c << 8) & 0xFFFFFFFF) ^ _TABLE[((c >> 24) ^ b) & 0xFF]
|
||||
|
||||
|
||||
def _feed_word(c: int, w: int) -> int:
|
||||
"""Feed one 32-bit word MSB-first (== its 4 big-endian bytes)."""
|
||||
c = _feed_byte(c, (w >> 24) & 0xFF)
|
||||
c = _feed_byte(c, (w >> 16) & 0xFF)
|
||||
c = _feed_byte(c, (w >> 8) & 0xFF)
|
||||
return _feed_byte(c, w & 0xFF)
|
||||
|
||||
|
||||
def _feed_byte_as_word(c: int, b: int) -> int:
|
||||
# word 0x000000bb: three zero bytes then b
|
||||
c = _TABLE[(c >> 24) & 0xFF] ^ ((c << 8) & 0xFFFFFFFF)
|
||||
c = _TABLE[(c >> 24) & 0xFF] ^ ((c << 8) & 0xFFFFFFFF)
|
||||
c = _TABLE[(c >> 24) & 0xFF] ^ ((c << 8) & 0xFFFFFFFF)
|
||||
return _feed_byte(c, b)
|
||||
|
||||
|
||||
def word_per_byte_crc(data: bytes, crc: int = INIT) -> int:
|
||||
for b in data:
|
||||
crc = _feed_byte_as_word(crc, b)
|
||||
return crc
|
||||
|
||||
|
||||
def dword_crc(data: bytes, crc: int = INIT) -> int:
|
||||
if len(data) % 4:
|
||||
raise ValueError("dword_crc needs a multiple of 4 bytes")
|
||||
for (w,) in struct.iter_unpack("<I", data):
|
||||
crc = _feed_word(crc, w)
|
||||
return crc
|
||||
|
||||
|
||||
def page_crc(page: bytes) -> int:
|
||||
"""CRC stored in the first 4 bytes of a page (``N.pa``) blob.
|
||||
|
||||
Input: page[4:], then datasize (LE32, header offset 4), numberobj (LE32, offset 12),
|
||||
and the header bytes at offsets 20 and 21 -- each byte fed as a word.
|
||||
"""
|
||||
datasize, = struct.unpack_from("<I", page, 4)
|
||||
nobj, = struct.unpack_from("<I", page, 12)
|
||||
tail = struct.pack("<II", datasize, nobj) + page[20:22]
|
||||
return word_per_byte_crc(page[4:] + tail)
|
||||
|
||||
|
||||
def main_crc(main: bytes) -> int:
|
||||
"""CRC stored in the first 4 bytes of the ``main.HMI`` project header blob.
|
||||
|
||||
Input: main[4:], then main[16:20] (model id), main[4:8], main[10], main[14].
|
||||
NOTE: the last two tail bytes were 0x21, 0x4F in every sample seen; they are taken from
|
||||
offsets 10 and 14 where those values live, but could also be constants (format version).
|
||||
"""
|
||||
tail = main[16:20] + main[4:8] + main[10:11] + main[14:15]
|
||||
return word_per_byte_crc(main[4:] + tail)
|
||||
|
||||
|
||||
def table_crc(table: bytes) -> int:
|
||||
"""Checksum stored right after the file table (count + entries)."""
|
||||
return _feed_word(dword_crc(table), TABLE_MAGIC)
|
||||
@@ -0,0 +1,195 @@
|
||||
"""Command line interface: ``python -m nxhmi <command> ...``"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
|
||||
from . import checksum, project
|
||||
from .container import HMIFile
|
||||
from .page import Page
|
||||
|
||||
|
||||
def cmd_info(a):
|
||||
h = HMIFile.load(a.hmi)
|
||||
t0, t1 = h.table_ok()
|
||||
print("file table: primary %s, backup %s" % ("ok" if t0 else "BAD", "ok" if t1 else "BAD"))
|
||||
for e in h.entries:
|
||||
flag = "deleted" if e.deleted else ""
|
||||
shown = e.name if not e.deleted else "(%s)" % e.name.encode("latin-1").decode("ascii", "replace").replace("�", "?").replace("\0", "?")
|
||||
line = "%-16s %8d bytes @0x%07X %s" % (shown, e.size, e.start, flag)
|
||||
if not e.deleted and e.name.endswith(".pa"):
|
||||
blob = h.read(e.name)
|
||||
ok = checksum.page_crc(blob) == int.from_bytes(blob[:4], "little")
|
||||
p = Page.parse(blob, verify=False)
|
||||
line += " page %-14s %3d components crc %s" % (p.name, len(p.components), "ok" if ok else "BAD")
|
||||
print(line)
|
||||
|
||||
|
||||
def cmd_verify(a):
|
||||
bad = 0
|
||||
for path in a.hmi:
|
||||
h = HMIFile.load(path)
|
||||
for e in h.live():
|
||||
blob = h.read(e.name)
|
||||
stored = int.from_bytes(blob[:4], "little")
|
||||
if e.name.endswith(".pa") and checksum.page_crc(blob) != stored:
|
||||
print("%s: %s page checksum BAD" % (path, e.name)); bad += 1
|
||||
if e.name == "main.HMI" and checksum.main_crc(blob) != stored:
|
||||
print("%s: main.HMI checksum BAD" % path); bad += 1
|
||||
t0, t1 = h.table_ok()
|
||||
if not (t0 and t1):
|
||||
print("%s: file table checksum BAD (primary %s, backup %s)" % (path, t0, t1)); bad += 1
|
||||
if not bad:
|
||||
print("%s: ok" % path)
|
||||
return 1 if bad else 0
|
||||
|
||||
|
||||
def cmd_decode(a):
|
||||
m = project.decode(a.hmi, a.out, a.encoding, not a.raw)
|
||||
print("decoded %d entries into %s" % (len(m["entries"]), a.out))
|
||||
|
||||
|
||||
def cmd_encode(a):
|
||||
project.encode(a.folder, a.hmi)
|
||||
print("wrote", a.hmi)
|
||||
|
||||
|
||||
def cmd_set(a):
|
||||
"""Set one attribute in place: nxhmi set file.HMI page objname attr value [-o out]"""
|
||||
h = HMIFile.load(a.hmi)
|
||||
for e in h.live():
|
||||
if not e.name.endswith(".pa"):
|
||||
continue
|
||||
p = Page.parse(h.read(e.name))
|
||||
if p.name != a.page:
|
||||
continue
|
||||
c = p.component(a.component)
|
||||
if c is None:
|
||||
sys.exit("no component %r on page %r" % (a.component, a.page))
|
||||
kind, _ = c.attr(a.attr).decoded()
|
||||
c.set(a.attr, a.value if kind in ("str", "hex") else int(a.value, 0))
|
||||
h.write(e.name, p.pack())
|
||||
h.save(a.out or a.hmi)
|
||||
print("set %s.%s.%s = %s" % (a.page, a.component, a.attr, a.value))
|
||||
return
|
||||
sys.exit("no page %r" % a.page)
|
||||
|
||||
|
||||
def cmd_add(a):
|
||||
"""Add a component: nxhmi add file.HMI page kind [name=value ...] [--name obj] [-o out]"""
|
||||
from . import components
|
||||
h = HMIFile.load(a.hmi)
|
||||
for e in h.live():
|
||||
if not e.name.endswith(".pa"):
|
||||
continue
|
||||
p = Page.parse(h.read(e.name))
|
||||
if p.name != a.page:
|
||||
continue
|
||||
kw = {}
|
||||
for item in a.attrs:
|
||||
k, _, v = item.partition("=")
|
||||
try:
|
||||
kw[k] = int(v, 0)
|
||||
except ValueError:
|
||||
kw[k] = v
|
||||
c = components.add(p, a.kind, a.name, **kw)
|
||||
h.write(e.name, p.pack())
|
||||
h.save(a.out or a.hmi)
|
||||
print("added %s (%s, id %d) to page %s" % (c.name, a.kind, c.get("id"), p.name))
|
||||
return
|
||||
sys.exit("no page %r" % a.page)
|
||||
|
||||
|
||||
def cmd_new_page(a):
|
||||
from . import project
|
||||
h = HMIFile.load(a.hmi)
|
||||
project.add_page(h, a.name)
|
||||
h.save(a.out or a.hmi)
|
||||
print("added page", a.name)
|
||||
|
||||
|
||||
def cmd_add_font(a):
|
||||
from . import fonts, project
|
||||
h = HMIFile.load(a.hmi)
|
||||
f = fonts.from_ttf(a.ttf, a.height, a.encoding, a.fixed_width)
|
||||
fid = project.add_font(h, f)
|
||||
h.save(a.out or a.hmi)
|
||||
print("added font id %d (%s, %d chars)" % (fid, f.name, len(f.glyphs)))
|
||||
|
||||
|
||||
def cmd_add_picture(a):
|
||||
from . import project
|
||||
h = HMIFile.load(a.hmi)
|
||||
with open(a.image, "rb") as f:
|
||||
pid = project.add_picture(h, f.read())
|
||||
h.save(a.out or a.hmi)
|
||||
print("added picture id", pid)
|
||||
|
||||
|
||||
def cmd_render(a):
|
||||
import os
|
||||
from .render import Renderer
|
||||
r = Renderer(HMIFile.load(a.hmi))
|
||||
names = [k for k in r.pages if isinstance(k, str)]
|
||||
todo = names if a.page in (None, "all") else [a.page]
|
||||
os.makedirs(a.out, exist_ok=True)
|
||||
for n in todo:
|
||||
path = os.path.join(a.out, "%s.png" % n)
|
||||
r.render(n).save(path)
|
||||
print("wrote", path)
|
||||
|
||||
|
||||
def cmd_kinds(a):
|
||||
from . import components
|
||||
for k in components.kinds():
|
||||
print(k)
|
||||
|
||||
|
||||
def cmd_dump(a):
|
||||
h = HMIFile.load(a.hmi)
|
||||
for e in h.live():
|
||||
if e.name.endswith(".pa"):
|
||||
p = Page.parse(h.read(e.name))
|
||||
if a.page and p.name != a.page:
|
||||
continue
|
||||
print(json.dumps(project.page_to_json(e.name, p, a.encoding, not a.raw), indent=1, ensure_ascii=False))
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(prog="nxhmi", description="Read, verify and write Nextion Editor .HMI projects")
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
s = sub.add_parser("info", help="list entries, pages and checksum status"); s.add_argument("hmi"); s.set_defaults(f=cmd_info)
|
||||
s = sub.add_parser("verify", help="check every checksum"); s.add_argument("hmi", nargs="+"); s.set_defaults(f=cmd_verify)
|
||||
s = sub.add_parser("decode", help="HMI -> folder of JSON/text"); s.add_argument("hmi"); s.add_argument("out")
|
||||
s.add_argument("--encoding", default="latin-1"); s.add_argument("--raw", action="store_true", help="numbers instead of names/colours")
|
||||
s.set_defaults(f=cmd_decode)
|
||||
s = sub.add_parser("encode", help="folder -> new HMI"); s.add_argument("folder"); s.add_argument("hmi"); s.set_defaults(f=cmd_encode)
|
||||
s = sub.add_parser("set", help="change one attribute")
|
||||
for n in ("hmi", "page", "component", "attr", "value"):
|
||||
s.add_argument(n)
|
||||
s.add_argument("-o", "--out"); s.set_defaults(f=cmd_set)
|
||||
s = sub.add_parser("add", help="add a component to a page (kind: see 'kinds')")
|
||||
s.add_argument("hmi"); s.add_argument("page"); s.add_argument("kind")
|
||||
s.add_argument("attrs", nargs="*", help="attribute=value, e.g. x=10 y=20 txt=Hi")
|
||||
s.add_argument("--name"); s.add_argument("-o", "--out"); s.set_defaults(f=cmd_add)
|
||||
s = sub.add_parser("render", help="render pages to PNG like the Editor's canvas (needs Pillow)")
|
||||
s.add_argument("hmi"); s.add_argument("out", help="output folder"); s.add_argument("--page", help="page name (default: all)")
|
||||
s.set_defaults(f=cmd_render)
|
||||
s = sub.add_parser("kinds", help="list component kinds that can be added"); s.set_defaults(f=cmd_kinds)
|
||||
s = sub.add_parser("add-font", help="rasterize a .ttf into a new font (needs Pillow)")
|
||||
s.add_argument("hmi"); s.add_argument("ttf"); s.add_argument("height", type=int)
|
||||
s.add_argument("--encoding", default="ascii", choices=["ascii", "iso-8859-1"])
|
||||
s.add_argument("--fixed-width", type=int); s.add_argument("-o", "--out"); s.set_defaults(f=cmd_add_font)
|
||||
s = sub.add_parser("add-picture", help="add a picture (png/jpg/bmp; needs Pillow)")
|
||||
s.add_argument("hmi"); s.add_argument("image"); s.add_argument("-o", "--out"); s.set_defaults(f=cmd_add_picture)
|
||||
s = sub.add_parser("new-page", help="add an empty page"); s.add_argument("hmi"); s.add_argument("name")
|
||||
s.add_argument("-o", "--out"); s.set_defaults(f=cmd_new_page)
|
||||
s = sub.add_parser("dump", help="print pages as JSON"); s.add_argument("hmi"); s.add_argument("--page")
|
||||
s.add_argument("--encoding", default="latin-1"); s.add_argument("--raw", action="store_true"); s.set_defaults(f=cmd_dump)
|
||||
a = ap.parse_args(argv)
|
||||
return a.f(a) or 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Create new components from the Editor's own defaults.
|
||||
|
||||
templates_basic.json / templates_intelligent.json hold, per component type, the full attribute
|
||||
list (name, kind, default) and event groups exactly as Nextion Editor writes a freshly placed
|
||||
component (regenerate with tools/make_templates.py). Basic types are available on every series;
|
||||
the Intelligent file adds the types that only exist there (video, audio, combobox, ...).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
from .page import Attr, Component, Group, Page
|
||||
|
||||
_HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
|
||||
def _load(fn):
|
||||
with open(os.path.join(_HERE, fn), encoding="utf-8") as f:
|
||||
return {int(k): v for k, v in json.load(f)["types"].items()}
|
||||
|
||||
|
||||
BASIC = _load("templates_basic.json")
|
||||
INTELLIGENT = _load("templates_intelligent.json")
|
||||
TYPES = dict(INTELLIGENT)
|
||||
TYPES.update(BASIC) # basic defaults win for shared types
|
||||
KINDS = {v["kind"]: k for k, v in TYPES.items()}
|
||||
INTELLIGENT_ONLY = sorted(v["kind"] for k, v in INTELLIGENT.items() if k not in BASIC)
|
||||
|
||||
|
||||
def kinds() -> list[str]:
|
||||
return sorted(KINDS)
|
||||
|
||||
|
||||
def _type(kind) -> dict:
|
||||
return TYPES[KINDS[kind] if isinstance(kind, str) else int(kind)]
|
||||
|
||||
|
||||
def make(kind, objname: str, id_: int, **attrs) -> Component:
|
||||
"""Build a component of ``kind`` (name like "button" or numeric type) with Editor defaults.
|
||||
|
||||
Keyword arguments set attributes (x=, y=, w=, h=, txt=, ...); endx/endy follow x/y/w/h.
|
||||
``events={"codesdown": ["page 1"]}`` sets event code.
|
||||
"""
|
||||
t = _type(kind)
|
||||
events = attrs.pop("events", {})
|
||||
comp = Component([Group("att", [Attr.encode(n, k, v) for n, k, v in t["att"]])] +
|
||||
[Group(g, []) for g in t["events"]])
|
||||
comp.set("objname", objname)
|
||||
comp.set("id", id_)
|
||||
for k, v in attrs.items():
|
||||
comp.set(k, v)
|
||||
_fix_ends(comp)
|
||||
for g, lines in events.items():
|
||||
comp.set_event(g, lines)
|
||||
return comp
|
||||
|
||||
|
||||
def _fix_ends(c: Component) -> None:
|
||||
names = {a.name for a in c.attrs()}
|
||||
if {"x", "w", "endx"} <= names:
|
||||
c.set("endx", c.get("x") + c.get("w") - 1)
|
||||
if {"y", "h", "endy"} <= names:
|
||||
c.set("endy", c.get("y") + c.get("h") - 1)
|
||||
|
||||
|
||||
def add(page: Page, kind, objname: str | None = None, **attrs) -> Component:
|
||||
"""Append a new component to ``page`` with the next free id and a unique objname."""
|
||||
t = _type(kind)
|
||||
used = {c.name for c in page.components}
|
||||
if objname is None:
|
||||
n = 0
|
||||
while "%s%d" % (t["prefix"], n) in used:
|
||||
n += 1
|
||||
objname = "%s%d" % (t["prefix"], n)
|
||||
elif objname in used:
|
||||
raise ValueError("objname %r already used on page %r" % (objname, page.name))
|
||||
next_id = max((c.get("id") or 0) for c in page.components) + 1 if page.components else 0
|
||||
comp = make(kind, objname, next_id, **attrs)
|
||||
page.components.append(comp)
|
||||
return comp
|
||||
|
||||
|
||||
def new_page(name: str, **attrs) -> Page:
|
||||
"""A page with only its page component (id 0). Defaults to a plain white background."""
|
||||
attrs.setdefault("sta", 1) # 1 = solid colour, 2 = picture
|
||||
attrs.setdefault("bco", 0xFFFF)
|
||||
return Page(name, [make(121, name, 0, **attrs)])
|
||||
@@ -0,0 +1,172 @@
|
||||
"""The .HMI container: a small file system with a checksummed, duplicated file table.
|
||||
|
||||
Layout (all offsets absolute, little-endian):
|
||||
|
||||
0x000000 file table: count(u32), count * 28-byte entries, then table checksum (u32)
|
||||
0x080000 exact backup copy of the file table (+ checksum)
|
||||
0x380000 u32 0xFFFFFFFF marker
|
||||
0x6FFFF8 b"ver21234"
|
||||
0x700000 entry data, packed back to back
|
||||
|
||||
Entry (28 bytes): name[16] (NUL padded), start(u32), size(u32), deleted(u8), 3 more bytes
|
||||
(not interpreted by us; kept as-is, written as 0 for new entries). A deleted entry also has
|
||||
the first byte of its name set to 0 -- the Editor matches entries by name, so the flag alone
|
||||
is not enough.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from . import checksum
|
||||
|
||||
TABLE_OFFSET = 0x000000
|
||||
BACKUP_TABLE_OFFSET = 0x080000
|
||||
MARKER_OFFSET = 0x380000
|
||||
VERSION_OFFSET = 0x6FFFF8
|
||||
VERSION_MAGIC = b"ver21234"
|
||||
DATA_OFFSET = 0x700000
|
||||
ENTRY_SIZE = 28
|
||||
MAX_TABLE_BYTES = BACKUP_TABLE_OFFSET - TABLE_OFFSET - 4
|
||||
|
||||
|
||||
class HMIError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Entry:
|
||||
name: str
|
||||
start: int
|
||||
size: int
|
||||
deleted: bool = False
|
||||
extra: bytes = b"\0\0\0" # the 3 trailing entry bytes
|
||||
raw_name: bytes = b"" # name exactly as stored (deleted entries are mangled)
|
||||
|
||||
def pack(self) -> bytes:
|
||||
nm = self.raw_name if self.raw_name else self.name.encode("latin-1")
|
||||
nm = nm[:16].ljust(16, b"\0")
|
||||
if self.deleted:
|
||||
nm = b"\0" + nm[1:]
|
||||
return nm + struct.pack("<IIB", self.start, self.size, 1 if self.deleted else 0) + self.extra[:3].ljust(3, b"\0")
|
||||
|
||||
|
||||
@dataclass
|
||||
class HMIFile:
|
||||
raw: bytearray
|
||||
entries: list[Entry] = field(default_factory=list)
|
||||
|
||||
# ------------------------------------------------------------------ reading
|
||||
@classmethod
|
||||
def load(cls, path) -> "HMIFile":
|
||||
with open(path, "rb") as f:
|
||||
return cls.from_bytes(f.read())
|
||||
|
||||
@classmethod
|
||||
def from_bytes(cls, data: bytes) -> "HMIFile":
|
||||
raw = bytearray(data)
|
||||
entries = cls._read_table(raw, TABLE_OFFSET)
|
||||
if entries is None:
|
||||
entries = cls._read_table(raw, BACKUP_TABLE_OFFSET)
|
||||
if entries is None:
|
||||
raise HMIError("both file tables are corrupt (checksum mismatch)")
|
||||
return cls(raw, entries)
|
||||
|
||||
@staticmethod
|
||||
def _read_table(raw: bytes, base: int):
|
||||
if len(raw) < base + 4:
|
||||
return None
|
||||
count, = struct.unpack_from("<I", raw, base)
|
||||
end = base + 4 + count * ENTRY_SIZE
|
||||
if count > MAX_TABLE_BYTES // ENTRY_SIZE or end + 4 > len(raw):
|
||||
return None
|
||||
stored, = struct.unpack_from("<I", raw, end)
|
||||
if checksum.table_crc(bytes(raw[base:end])) != stored:
|
||||
return None
|
||||
out = []
|
||||
for i in range(count):
|
||||
off = base + 4 + i * ENTRY_SIZE
|
||||
nm, start, size, deleted = struct.unpack_from("<16sIIB", raw, off)
|
||||
extra = bytes(raw[off + 25: off + 28])
|
||||
out.append(Entry(nm.rstrip(b"\0").decode("latin-1"), start, size, bool(deleted), extra, nm))
|
||||
return out
|
||||
|
||||
def live(self) -> list[Entry]:
|
||||
return [e for e in self.entries if not e.deleted]
|
||||
|
||||
def find(self, name: str) -> Entry | None:
|
||||
for e in self.entries:
|
||||
if not e.deleted and e.name == name:
|
||||
return e
|
||||
return None
|
||||
|
||||
def read(self, name: str) -> bytes:
|
||||
e = self.find(name)
|
||||
if e is None:
|
||||
raise KeyError(name)
|
||||
return bytes(self.raw[e.start:e.start + e.size])
|
||||
|
||||
def names(self) -> list[str]:
|
||||
return [e.name for e in self.live()]
|
||||
|
||||
def table_ok(self) -> tuple[bool, bool]:
|
||||
return (self._read_table(self.raw, TABLE_OFFSET) is not None,
|
||||
self._read_table(self.raw, BACKUP_TABLE_OFFSET) is not None)
|
||||
|
||||
# ------------------------------------------------------------------ writing
|
||||
def write(self, name: str, data: bytes) -> None:
|
||||
"""Replace (or add) an entry the way the Editor does: append the data at the end of the
|
||||
file, mark the old entry deleted, add a new entry. Call fix_checksums()/save() after."""
|
||||
old = self.find(name)
|
||||
start = len(self.raw)
|
||||
self.raw += data
|
||||
if old is not None:
|
||||
old.deleted = True
|
||||
self.entries.append(Entry(name, start, len(data)))
|
||||
|
||||
def delete(self, name: str) -> None:
|
||||
e = self.find(name)
|
||||
if e is None:
|
||||
raise KeyError(name)
|
||||
e.deleted = True
|
||||
|
||||
def _table_bytes(self) -> bytes:
|
||||
return struct.pack("<I", len(self.entries)) + b"".join(e.pack() for e in self.entries)
|
||||
|
||||
def _store_tables(self) -> None:
|
||||
tbl = self._table_bytes()
|
||||
if len(tbl) > MAX_TABLE_BYTES:
|
||||
raise HMIError("file table too large")
|
||||
blob = tbl + struct.pack("<I", checksum.table_crc(tbl))
|
||||
for base in (TABLE_OFFSET, BACKUP_TABLE_OFFSET):
|
||||
# clear the old table area (old one may have been longer)
|
||||
old_count, = struct.unpack_from("<I", self.raw, base)
|
||||
old_len = min(4 + old_count * ENTRY_SIZE + 4, MAX_TABLE_BYTES)
|
||||
self.raw[base:base + max(old_len, len(blob))] = bytes(max(old_len, len(blob)))
|
||||
self.raw[base:base + len(blob)] = blob
|
||||
|
||||
def to_bytes(self) -> bytes:
|
||||
self._store_tables()
|
||||
return bytes(self.raw)
|
||||
|
||||
def save(self, path) -> None:
|
||||
with open(path, "wb") as f:
|
||||
f.write(self.to_bytes())
|
||||
|
||||
def compacted(self) -> "HMIFile":
|
||||
"""A fresh file containing only the live entries, packed from DATA_OFFSET."""
|
||||
return build([(e.name, self.read(e.name)) for e in self.live()])
|
||||
|
||||
|
||||
def build(items: list[tuple[str, bytes]]) -> HMIFile:
|
||||
"""Create a new .HMI container from (name, data) pairs, in the given order."""
|
||||
raw = bytearray(DATA_OFFSET)
|
||||
struct.pack_into("<I", raw, MARKER_OFFSET, 0xFFFFFFFF)
|
||||
raw[VERSION_OFFSET:VERSION_OFFSET + 8] = VERSION_MAGIC
|
||||
entries = []
|
||||
for name, data in items:
|
||||
entries.append(Entry(name, len(raw), len(data)))
|
||||
raw += data
|
||||
f = HMIFile(raw, entries)
|
||||
f._store_tables()
|
||||
return f
|
||||
@@ -0,0 +1,86 @@
|
||||
"""Readable names for attribute values.
|
||||
|
||||
All value lists come from Nextion Editor 1.68's own attribute notes (read via UI Automation from the
|
||||
Attribute panel), e.g. "Horizontal alignment:0-Left;1-Center;2-Right". A few attributes mean
|
||||
different things per component type, hence the per-type overrides.
|
||||
|
||||
Colours (RGB565 in the file) are shown as "#rrggbb"; conversion is exact in both directions for
|
||||
values that came from a file (5/6-bit channels are expanded by bit replication).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# attribute -> {value: label}, valid for every component type unless overridden below
|
||||
GENERAL = {
|
||||
"vscope": {0: "local", 1: "global"},
|
||||
"sta": {0: "crop image", 1: "solid color", 2: "image"},
|
||||
"style": {0: "flat", 1: "border", 2: "3D_Down", 3: "3D_Up"},
|
||||
"xcen": {0: "left", 1: "center", 2: "right"},
|
||||
"ycen": {0: "up", 1: "center", 2: "down"},
|
||||
"isbr": {0: "false", 1: "true"},
|
||||
"pw": {0: "character", 1: "password"},
|
||||
}
|
||||
|
||||
# component type -> attribute -> {value: label}
|
||||
BY_TYPE = {
|
||||
121: {"sta": {0: "no background", 1: "solid color", 2: "image"}}, # page
|
||||
98: {"style": {0: "flat", 1: "border", 2: "3D_Down", 3: "3D_Up", 4: "3D_Auto"}}, # button
|
||||
53: {"style": {0: "flat", 1: "border", 2: "3D_Down", 3: "3D_Up", 4: "3D_Auto"}}, # dual-state button
|
||||
54: {"format": {0: "decimal", 1: "currency", 2: "hex"}}, # number
|
||||
59: {"format": {0: "decimal", 1: "currency", 2: "hex"}}, # xfloat
|
||||
55: {"dir": {0: "left to right", 1: "right to left", 2: "up to down", 3: "down to up"},
|
||||
"en": {0: "disable", 1: "enable"}}, # scrolling text
|
||||
51: {"en": {0: "disable", 1: "enable"}}, # timer
|
||||
52: {"sta": {0: "number", 1: "string"}}, # variable
|
||||
1: {"mode": {0: "horizontal", 1: "vertical"}, "psta": {0: "solid", 1: "image"}}, # slider
|
||||
106: {"sta": {0: "solid color", 1: "image"}, "dez": {0: "horizontal", 1: "vertical"}}, # progress bar
|
||||
0: {"dir": {0: "left to right", 1: "right to left", 2: "right align"}}, # waveform
|
||||
58: {"sta": {0: "none", 1: "has"}}, # qrcode (logo)
|
||||
}
|
||||
|
||||
COLOR_ATTRS = {"bco", "bco1", "bco2", "pco", "pco0", "pco1", "pco2", "pco3", "borderc", "gdc"}
|
||||
|
||||
|
||||
def table(ctype: int | None, attr: str) -> dict | None:
|
||||
if ctype is not None and attr in BY_TYPE.get(ctype, {}):
|
||||
return BY_TYPE[ctype][attr]
|
||||
return GENERAL.get(attr)
|
||||
|
||||
|
||||
def rgb565_to_hex(v: int) -> str:
|
||||
r, g, b = v >> 11, (v >> 5) & 63, v & 31
|
||||
return "#%02x%02x%02x" % (r << 3 | r >> 2, g << 2 | g >> 4, b << 3 | b >> 2)
|
||||
|
||||
|
||||
def hex_to_rgb565(s: str) -> int:
|
||||
s = s.lstrip("#")
|
||||
r, g, b = int(s[0:2], 16), int(s[2:4], 16), int(s[4:6], 16)
|
||||
return (r >> 3) << 11 | (g >> 2) << 5 | (b >> 3)
|
||||
|
||||
|
||||
def to_label(ctype: int | None, attr: str, kind: str, value):
|
||||
"""int -> readable value (label / '#rrggbb'), or the value unchanged."""
|
||||
if kind not in ("u8", "u16", "u32"):
|
||||
return value
|
||||
if attr in COLOR_ATTRS and kind == "u16":
|
||||
return rgb565_to_hex(value)
|
||||
t = table(ctype, attr)
|
||||
if t and value in t:
|
||||
return t[value]
|
||||
return value
|
||||
|
||||
|
||||
def from_label(ctype: int | None, attr: str, kind: str, value):
|
||||
"""Inverse of to_label; accepts plain ints too."""
|
||||
if not isinstance(value, str) or kind not in ("u8", "u16", "u32"):
|
||||
return value
|
||||
if value.startswith("#") and len(value) == 7:
|
||||
return hex_to_rgb565(value)
|
||||
t = table(ctype, attr)
|
||||
if t:
|
||||
for k, v in t.items():
|
||||
if v.lower() == value.lower():
|
||||
return k
|
||||
try:
|
||||
return int(value, 0)
|
||||
except ValueError:
|
||||
raise ValueError("unknown value %r for attribute %r" % (value, attr))
|
||||
@@ -0,0 +1,213 @@
|
||||
"""Nextion fonts (``N.zi`` entries), file format version 6, black/white glyphs.
|
||||
|
||||
Header (44 bytes, little-endian)::
|
||||
|
||||
0 4 magic 04 FF 00 0B (byte 3: 0x0B -- 0x0A "vertical" in older docs; OPEN)
|
||||
4 2 encoding (1 ascii, 3 iso-8859-1, ...)
|
||||
6 1 character width (fixed-width fonts; per-glyph width in the map)
|
||||
7 1 character height
|
||||
8 1 multi-byte first-byte start 9 1 ... end
|
||||
10 1 code range start 11 1 code range end
|
||||
12 4 character count
|
||||
16 1 format version (6)
|
||||
17 1 name length
|
||||
18 1 name length (again)
|
||||
19 1 0
|
||||
20 4 length of name + map + glyph data
|
||||
24 4 start of name (0x2C)
|
||||
28 16 unknown (kept as-is)
|
||||
44 . name, then character map, then glyph data
|
||||
|
||||
Character map: ``count`` entries of 10 bytes::
|
||||
|
||||
0 2 character code 2 1 glyph width 3 1 ? 4 1 ?
|
||||
5 3 glyph data offset (relative to the start of the map)
|
||||
8 2 glyph data length
|
||||
|
||||
Glyph data: one mode byte (0x01 = black/white), then run-length codes. Pixels are scanned
|
||||
column by column (x = 0..w-1), each column from the bottom row up -- the same 90-degree panel
|
||||
rotation as pictures. Codes (top two bits = op)::
|
||||
|
||||
00 0xxxxx x transparent 00 1xxxxx x ink
|
||||
01 0xxxxx x transparent + 1 ink 01 1xxxxx x transparent + 2 ink
|
||||
10 0xxxxx x transparent + 3 ink 10 1xxxxx x transparent + 4 ink
|
||||
11 tttiii ttt transparent + iii ink
|
||||
|
||||
Runs continue across column boundaries.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
HEADER_SIZE = 0x2C
|
||||
MAP_ENTRY = 10
|
||||
|
||||
|
||||
@dataclass
|
||||
class Glyph:
|
||||
code: int
|
||||
width: int
|
||||
pixels: list # rows top->bottom of 0/1 (len = height, each len = width)
|
||||
map_extra: bytes = b"\0\0" # map bytes 3..4
|
||||
mode: int = 1
|
||||
|
||||
|
||||
@dataclass
|
||||
class Font:
|
||||
name: str
|
||||
width: int
|
||||
height: int
|
||||
encoding: int
|
||||
first: int
|
||||
last: int
|
||||
glyphs: list = field(default_factory=list)
|
||||
header: bytes = b"" # original 44-byte header, for fields not modelled
|
||||
|
||||
# ------------------------------------------------------------------ decode
|
||||
@classmethod
|
||||
def parse(cls, blob: bytes) -> "Font":
|
||||
if blob[:3] != b"\x04\xff\x00":
|
||||
raise ValueError("not a .zi font")
|
||||
if blob[16] != 6:
|
||||
raise ValueError("unsupported .zi version %d (only 6 is implemented)" % blob[16])
|
||||
w, h = blob[6], blob[7]
|
||||
count, = struct.unpack_from("<I", blob, 12)
|
||||
nlen = blob[17]
|
||||
start, = struct.unpack_from("<I", blob, 24)
|
||||
name = blob[start:start + nlen].decode("latin-1")
|
||||
m = start + nlen
|
||||
f = cls(name, w, h, struct.unpack_from("<H", blob, 4)[0], blob[10], blob[11], [], bytes(blob[:HEADER_SIZE]))
|
||||
for i in range(count):
|
||||
e = blob[m + MAP_ENTRY * i: m + MAP_ENTRY * (i + 1)]
|
||||
code, gw = struct.unpack_from("<HB", e, 0)
|
||||
off = e[5] | e[6] << 8 | e[7] << 16
|
||||
ln, = struct.unpack_from("<H", e, 8)
|
||||
data = blob[m + off: m + off + ln]
|
||||
f.glyphs.append(Glyph(code, gw, decode_glyph(data, gw, h), bytes(e[3:5]), data[0]))
|
||||
return f
|
||||
|
||||
# ------------------------------------------------------------------ encode
|
||||
def pack(self) -> bytes:
|
||||
name = self.name.encode("latin-1")
|
||||
bodies = [bytes([g.mode]) + encode_glyph(g.pixels, g.width, self.height) for g in self.glyphs]
|
||||
mp = bytearray()
|
||||
off = MAP_ENTRY * len(self.glyphs)
|
||||
for g, b in zip(self.glyphs, bodies):
|
||||
mp += struct.pack("<HB", g.code, g.width) + g.map_extra[:2].ljust(2, b"\0")
|
||||
mp += bytes([off & 0xFF, (off >> 8) & 0xFF, off >> 16]) + struct.pack("<H", len(b))
|
||||
off += len(b)
|
||||
payload = name + bytes(mp) + b"".join(bodies)
|
||||
hdr = bytearray(self.header or bytes(HEADER_SIZE))
|
||||
hdr[0:4] = hdr[0:4] if self.header else b"\x04\xff\x00\x0b"
|
||||
struct.pack_into("<H", hdr, 4, self.encoding)
|
||||
hdr[6], hdr[7], hdr[10], hdr[11] = self.width, self.height, self.first, self.last
|
||||
struct.pack_into("<I", hdr, 12, len(self.glyphs))
|
||||
hdr[16], hdr[17], hdr[18] = 6, len(name), len(name)
|
||||
struct.pack_into("<II", hdr, 20, len(payload), HEADER_SIZE)
|
||||
return bytes(hdr) + payload
|
||||
|
||||
def glyph(self, ch) -> Glyph | None:
|
||||
code = ord(ch) if isinstance(ch, str) else ch
|
||||
for g in self.glyphs:
|
||||
if g.code == code:
|
||||
return g
|
||||
return None
|
||||
|
||||
|
||||
def _scan_order(w: int, h: int):
|
||||
for x in range(w):
|
||||
for y in range(h - 1, -1, -1):
|
||||
yield x, y
|
||||
|
||||
|
||||
def decode_glyph(data: bytes, w: int, h: int) -> list:
|
||||
stream = []
|
||||
for b in data[1:]:
|
||||
op, bit, x = b >> 6, (b >> 5) & 1, b & 0x1F
|
||||
if op == 0:
|
||||
stream += [bit] * x
|
||||
elif op == 3:
|
||||
stream += [0] * ((b >> 3) & 7) + [1] * (b & 7)
|
||||
else:
|
||||
stream += [0] * x + [1] * (op * 2 - 1 + bit)
|
||||
rows = [[0] * w for _ in range(h)]
|
||||
for v, (x, y) in zip(stream, _scan_order(w, h)):
|
||||
rows[y][x] = v
|
||||
return rows
|
||||
|
||||
|
||||
def encode_glyph(rows: list, w: int, h: int) -> bytes:
|
||||
"""Run-length encode a glyph (rows top->bottom). Greedy, see docs for the code table."""
|
||||
s = [rows[y][x] for x, y in _scan_order(w, h)]
|
||||
out = bytearray()
|
||||
i, n = 0, len(s)
|
||||
while i < n:
|
||||
t = 0
|
||||
while i + t < n and s[i + t] == 0:
|
||||
t += 1
|
||||
k = 0
|
||||
while i + t + k < n and s[i + t + k] == 1:
|
||||
k += 1
|
||||
if t == 0: # ink run
|
||||
run = min(k, 31)
|
||||
out.append(0x20 | run); i += run; continue
|
||||
if k == 0: # transparent up to end
|
||||
run = min(t, 31)
|
||||
out.append(run); i += run; continue
|
||||
# The Editor's choice (reproduces its output byte for byte): "x transparent + 1..4 ink" when
|
||||
# it fits, else "ttt transparent + iii ink", else a plain transparent run.
|
||||
if t <= 31 and 1 <= k <= 4:
|
||||
op, bit = (k + 1) // 2, (k + 1) % 2
|
||||
out.append(op << 6 | bit << 5 | t); i += t + k; continue
|
||||
if t <= 7 and k <= 7:
|
||||
out.append(0xC0 | t << 3 | k); i += t + k; continue
|
||||
run = min(t, 31)
|
||||
out.append(run); i += run
|
||||
return bytes(out)
|
||||
|
||||
|
||||
ENCODINGS = {"ascii": (1, 0x20, 0x7E), "iso-8859-1": (3, 0x20, 0xFF)}
|
||||
|
||||
|
||||
def from_ttf(path: str | None, height: int, encoding: str = "ascii", fixed_width: int | None = None,
|
||||
name: str | None = None, threshold: int = 128) -> "Font":
|
||||
"""Rasterize a TrueType/OpenType font into a black/white Nextion font (needs Pillow).
|
||||
|
||||
``path=None`` uses Pillow's bundled default font (Aileron Regular, CC0) -- handy for tests and
|
||||
demos. The font size is chosen so ascent + descent fills ``height`` pixels. Glyph widths follow
|
||||
the font's advance widths unless ``fixed_width`` is given.
|
||||
"""
|
||||
import os
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
enc, first, last = ENCODINGS[encoding]
|
||||
def load(size):
|
||||
return ImageFont.load_default(size=size) if path is None else ImageFont.truetype(path, size)
|
||||
|
||||
size = height
|
||||
while size > 4:
|
||||
f = load(size)
|
||||
a, d = f.getmetrics()
|
||||
if a + d <= height:
|
||||
break
|
||||
size -= 1
|
||||
ascent, descent = f.getmetrics()
|
||||
top = (height - ascent - descent) // 2
|
||||
glyphs = []
|
||||
for code in range(first, last + 1):
|
||||
ch = bytes([code]).decode("latin-1")
|
||||
adv = fixed_width or max(1, int(round(f.getlength(ch))))
|
||||
img = Image.new("L", (adv, height), 0)
|
||||
ImageDraw.Draw(img).text((0, top), ch, font=f, fill=255)
|
||||
px = img.load()
|
||||
rows = [[1 if px[x, y] >= threshold else 0 for x in range(adv)] for y in range(height)]
|
||||
glyphs.append(Glyph(code, adv, rows))
|
||||
width = fixed_width or max(g.width for g in glyphs)
|
||||
stem = "Aileron" if path is None else os.path.splitext(os.path.basename(path))[0]
|
||||
base = name or "%s-%d%s" % (stem, height, encoding)
|
||||
hdr = bytearray(HEADER_SIZE)
|
||||
hdr[0:4] = b"\x04\xff\x00\x0b"
|
||||
hdr[0x1C] = last
|
||||
hdr[0x20] = 0x0B
|
||||
struct.pack_into("<I", hdr, 0x24, len(glyphs))
|
||||
return Font(base[:255], width, height, enc, first, last, glyphs, bytes(hdr))
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Display models: id stored in main.HMI (offset 16), series byte (offset 11), native resolution.
|
||||
|
||||
Only series whose series byte was confirmed in the Editor are listed (Basic = 0, Intelligent = 3).
|
||||
Model ids are the 32-bit values the Editor writes for each model.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
# name: (model id, series byte, width, height)
|
||||
MODELS = {
|
||||
"NX3224T024_011": (0xF59677A7, 0, 320, 240),
|
||||
"NX3224T028_011": (0x1443383B, 0, 320, 240),
|
||||
"NX4024T032_011": (0x6D494DA9, 0, 400, 240),
|
||||
"NX4832T035_011": (0xB23BC018, 0, 480, 320),
|
||||
"NX4827T043_011": (0xCA296EB1, 0, 480, 272),
|
||||
"NX8048T050_011": (0x87AD3AE3, 0, 800, 480),
|
||||
"NX8048T070_011": (0x081FBDCC, 0, 800, 480),
|
||||
"NX4827P043_011": (0x181169DA, 3, 480, 272),
|
||||
"NX8048P050_011": (0x55953D88, 3, 800, 480),
|
||||
"NX8048P070_011": (0xDA27BAA7, 3, 800, 480),
|
||||
"NX1060P070_011": (0xC43473C2, 3, 1024, 600),
|
||||
"NX1060P101_011": (0x4FC44FA0, 3, 1024, 600),
|
||||
}
|
||||
BY_ID = {v[0]: k for k, v in MODELS.items()}
|
||||
SERIES = {0: "Basic", 3: "Intelligent"}
|
||||
|
||||
# main.HMI text-encoding index (offset 12). Only the value seen in real projects is listed.
|
||||
ENCODINGS = {"iso-8859-1": 1}
|
||||
|
||||
|
||||
def lookup(model: str):
|
||||
if model not in MODELS:
|
||||
raise KeyError("unknown model %r; known: %s" % (model, ", ".join(sorted(MODELS))))
|
||||
return MODELS[model]
|
||||
@@ -0,0 +1,228 @@
|
||||
"""Pages (``N.pa`` entries): header, component table, components.
|
||||
|
||||
Page blob layout (little-endian):
|
||||
|
||||
0 u32 crc (checksum.page_crc)
|
||||
4 u32 datasize (= len(blob))
|
||||
8 u32 infoaddr (= 56, start of the component table)
|
||||
12 u32 numberobj (component count)
|
||||
16 u32 password
|
||||
20 u8 locked
|
||||
21 u8 unknown (0x4F in every file seen)
|
||||
22 u8 version (0x21 = 33 in every file seen)
|
||||
23 u8 unknown
|
||||
24 16s page name
|
||||
40 16s reserved
|
||||
56 numberobj * (u32 offset, u32 size, u32 unknown) -- offset relative to byte 56
|
||||
... component data
|
||||
|
||||
Component data is a sequence of length-prefixed records (u32 len + bytes) ending with an empty
|
||||
record. Records are grouped: a header record ``b"<group>-<n>"`` is followed by n records.
|
||||
Group ``att`` holds attributes (16-byte NUL padded name + value); the other groups
|
||||
(``codesload``, ``codesdown``, ``codesup``, ``codestimer``, ...) hold event code lines.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
from . import checksum
|
||||
|
||||
HEADER_SIZE = 56
|
||||
TABLE_ENTRY = 12
|
||||
|
||||
# Text attributes: objname, plus every attribute that has a length-limit companion in the same
|
||||
# component (txt/txt_maxl, path/path_m, dir/dir_m, filter/filter_m, format/format_m, ...).
|
||||
# The same name can be text in one component and a number in another (e.g. `dir`, `format`).
|
||||
# Everything else is an unsigned little-endian integer of 1, 2 or 4 bytes.
|
||||
ALWAYS_STRING = {"objname"}
|
||||
|
||||
|
||||
def _string_names(names) -> set:
|
||||
names = set(names)
|
||||
return {n for n in names if n in ALWAYS_STRING or n + "_m" in names or n + "_maxl" in names}
|
||||
|
||||
|
||||
@dataclass
|
||||
class Attr:
|
||||
name: str
|
||||
value: bytes
|
||||
string: bool = False
|
||||
|
||||
def decoded(self, encoding: str = "latin-1"):
|
||||
if self.string:
|
||||
return ("str", self.value.decode(encoding))
|
||||
n = len(self.value)
|
||||
if n in (1, 2, 4):
|
||||
return ({1: "u8", 2: "u16", 4: "u32"}[n], int.from_bytes(self.value, "little"))
|
||||
return ("hex", self.value.hex())
|
||||
|
||||
@staticmethod
|
||||
def encode(name: str, kind: str, value, encoding: str = "latin-1") -> "Attr":
|
||||
if kind == "str":
|
||||
return Attr(name, value.encode(encoding), True)
|
||||
if kind in ("u8", "u16", "u32"):
|
||||
n = {"u8": 1, "u16": 2, "u32": 4}[kind]
|
||||
v = int(value)
|
||||
if v < 0: # signed values (e.g. number.val) are stored two's complement
|
||||
v &= (1 << (8 * n)) - 1
|
||||
return Attr(name, v.to_bytes(n, "little"))
|
||||
if kind == "hex":
|
||||
return Attr(name, bytes.fromhex(value))
|
||||
raise ValueError(kind)
|
||||
|
||||
def pack(self) -> bytes:
|
||||
return self.name.encode("latin-1")[:16].ljust(16, b"\0") + self.value
|
||||
|
||||
|
||||
@dataclass
|
||||
class Group:
|
||||
name: str # "att", "codesdown", ...
|
||||
records: list # list[Attr] for "att", list[bytes] for code groups
|
||||
|
||||
|
||||
@dataclass
|
||||
class Component:
|
||||
groups: list[Group] = field(default_factory=list)
|
||||
table_extra: int = 0 # third u32 of the component-table entry
|
||||
trailing: bytes = b"" # bytes after the terminating empty record (normally none)
|
||||
|
||||
# --- convenience ------------------------------------------------------
|
||||
def attrs(self) -> list[Attr]:
|
||||
for g in self.groups:
|
||||
if g.name == "att":
|
||||
return g.records
|
||||
return []
|
||||
|
||||
def attr(self, name: str) -> Attr | None:
|
||||
for a in self.attrs():
|
||||
if a.name == name:
|
||||
return a
|
||||
return None
|
||||
|
||||
def get(self, name: str, encoding: str = "latin-1"):
|
||||
a = self.attr(name)
|
||||
return None if a is None else a.decoded(encoding)[1]
|
||||
|
||||
def set(self, name: str, value, encoding: str = "latin-1") -> None:
|
||||
a = self.attr(name)
|
||||
if a is None:
|
||||
raise KeyError(name)
|
||||
kind, _ = a.decoded(encoding)
|
||||
if kind == "hex" and not isinstance(value, (bytes, str)):
|
||||
raise ValueError("raw attribute; pass hex string")
|
||||
a.value = Attr.encode(name, kind, value, encoding).value
|
||||
|
||||
def event(self, group: str) -> list[str] | None:
|
||||
for g in self.groups:
|
||||
if g.name == group:
|
||||
return [r.decode("latin-1") for r in g.records]
|
||||
return None
|
||||
|
||||
def set_event(self, group: str, lines: list[str]) -> None:
|
||||
for g in self.groups:
|
||||
if g.name == group:
|
||||
g.records = [ln.encode("latin-1") for ln in lines]
|
||||
return
|
||||
self.groups.append(Group(group, [ln.encode("latin-1") for ln in lines]))
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return self.get("objname") or ""
|
||||
|
||||
# --- (de)serialization -------------------------------------------------
|
||||
@classmethod
|
||||
def parse(cls, data: bytes, table_extra: int = 0) -> "Component":
|
||||
recs = []
|
||||
p = 0
|
||||
while p < len(data):
|
||||
n, = struct.unpack_from("<I", data, p)
|
||||
rec = data[p + 4:p + 4 + n]
|
||||
p += 4 + n
|
||||
if n == 0:
|
||||
break
|
||||
recs.append(rec)
|
||||
trailing = data[p:]
|
||||
groups = []
|
||||
i = 0
|
||||
while i < len(recs):
|
||||
gname, cnt = recs[i].rsplit(b"-", 1)
|
||||
cnt = int(cnt)
|
||||
body = recs[i + 1:i + 1 + cnt]
|
||||
gname = gname.decode("latin-1")
|
||||
if gname == "att":
|
||||
body = [Attr(r[:16].rstrip(b"\0").decode("latin-1"), r[16:]) for r in body]
|
||||
strs = _string_names(a.name for a in body)
|
||||
for a in body:
|
||||
a.string = a.name in strs
|
||||
groups.append(Group(gname, list(body)))
|
||||
i += 1 + cnt
|
||||
return cls(groups, table_extra, trailing)
|
||||
|
||||
def pack(self) -> bytes:
|
||||
out = bytearray()
|
||||
|
||||
def rec(b: bytes):
|
||||
out.extend(struct.pack("<I", len(b)))
|
||||
out.extend(b)
|
||||
|
||||
for g in self.groups:
|
||||
rec(("%s-%d" % (g.name, len(g.records))).encode("latin-1"))
|
||||
for r in g.records:
|
||||
rec(r.pack() if isinstance(r, Attr) else r)
|
||||
rec(b"")
|
||||
out.extend(self.trailing)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Page:
|
||||
name: str
|
||||
components: list[Component]
|
||||
password: int = 0
|
||||
locked: int = 0
|
||||
b21: int = 0x4F
|
||||
version: int = 0x21
|
||||
b23: int = 0
|
||||
reserved: bytes = bytes(16)
|
||||
header_extra: bytes = b"" # unused; kept for symmetry
|
||||
|
||||
@classmethod
|
||||
def parse(cls, blob: bytes, verify: bool = True) -> "Page":
|
||||
if len(blob) < HEADER_SIZE:
|
||||
raise ValueError("page too short")
|
||||
crc, datasize, infoaddr, nobj, password = struct.unpack_from("<IIIII", blob, 0)
|
||||
locked, b21, version, b23 = blob[20], blob[21], blob[22], blob[23]
|
||||
name = blob[24:40].rstrip(b"\0").decode("latin-1")
|
||||
reserved = bytes(blob[40:56])
|
||||
if verify and crc != checksum.page_crc(blob):
|
||||
raise ValueError("page %r: checksum mismatch" % name)
|
||||
comps = []
|
||||
for i in range(nobj):
|
||||
off, size, extra = struct.unpack_from("<III", blob, infoaddr + TABLE_ENTRY * i)
|
||||
start = infoaddr + off
|
||||
comps.append(Component.parse(blob[start:start + size], extra))
|
||||
return cls(name, comps, password, locked, b21, version, b23, reserved)
|
||||
|
||||
def pack(self) -> bytes:
|
||||
bodies = [c.pack() for c in self.components]
|
||||
table = bytearray()
|
||||
off = TABLE_ENTRY * len(bodies)
|
||||
for c, b in zip(self.components, bodies):
|
||||
table += struct.pack("<III", off, len(b), c.table_extra)
|
||||
off += len(b)
|
||||
total = HEADER_SIZE + len(table) + sum(len(b) for b in bodies)
|
||||
hdr = bytearray(HEADER_SIZE)
|
||||
struct.pack_into("<IIIII", hdr, 0, 0, total, HEADER_SIZE, len(bodies), self.password)
|
||||
hdr[20], hdr[21], hdr[22], hdr[23] = self.locked, self.b21, self.version, self.b23
|
||||
hdr[24:40] = self.name.encode("latin-1")[:16].ljust(16, b"\0")
|
||||
hdr[40:56] = self.reserved[:16].ljust(16, b"\0")
|
||||
blob = bytearray(hdr + table + b"".join(bodies))
|
||||
struct.pack_into("<I", blob, 0, checksum.page_crc(bytes(blob)))
|
||||
return bytes(blob)
|
||||
|
||||
def component(self, objname: str) -> Component | None:
|
||||
for c in self.components:
|
||||
if c.name == objname:
|
||||
return c
|
||||
return None
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Pictures: ``N.i`` (what the display uses) and ``N.is`` (the original source file).
|
||||
|
||||
``N.is`` header (27 bytes) + the original image file, unchanged::
|
||||
|
||||
0 4 0A 64 01 01
|
||||
4 4 0
|
||||
8 4 27 (data offset)
|
||||
12 2 width 14 2 height
|
||||
16 4 length of the embedded file
|
||||
20 4 0
|
||||
24 3 file type, e.g. b"png"
|
||||
27 . the file
|
||||
|
||||
``N.i`` header (24 bytes) + pixels::
|
||||
|
||||
0 4 0B 64 01 <format> format 0 = raw RGB565 (Basic series), 4 = compressed (Intelligent; OPEN)
|
||||
4 4 0
|
||||
8 4 24 (data offset)
|
||||
12 2 width 14 2 height
|
||||
16 4 data length (format 0: width * height * 2)
|
||||
20 4 0
|
||||
|
||||
Format 0 pixels are RGB565 little-endian, converted by plain truncation (r>>3, g>>2, b>>3) and
|
||||
stored in the panel's native order: rotated 90 degrees, i.e. for each source column x, the rows
|
||||
from bottom to top -- byte offset 2 * (x * height + (height - 1 - y)). Verified pixel-exact against
|
||||
Editor output for a 480x320 and a 64x64 picture on a project with display direction 270 (OPEN:
|
||||
other directions, main.HMI byte 13).
|
||||
|
||||
Pillow is only needed for converting to/from image files.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import struct
|
||||
|
||||
IS_MAGIC = b"\x0a\x64\x01\x01"
|
||||
I_MAGIC = b"\x0b\x64\x01"
|
||||
|
||||
|
||||
def source_info(blob: bytes) -> dict:
|
||||
w, h, n = struct.unpack_from("<HHI", blob, 12)
|
||||
return {"width": w, "height": h, "type": blob[24:27].rstrip(b"\0").decode("latin-1"), "length": n}
|
||||
|
||||
|
||||
def source_file(blob: bytes) -> bytes:
|
||||
"""The original image file embedded in an ``N.is`` entry."""
|
||||
off, = struct.unpack_from("<I", blob, 8)
|
||||
n, = struct.unpack_from("<I", blob, 16)
|
||||
return blob[off:off + n]
|
||||
|
||||
|
||||
def make_source(data: bytes, width: int, height: int, ftype: str = "png") -> bytes:
|
||||
hdr = IS_MAGIC + struct.pack("<IIHHII", 0, 27, width, height, len(data), 0) + ftype.encode()[:3].ljust(3, b"\0")
|
||||
return hdr + data
|
||||
|
||||
|
||||
def info(blob: bytes) -> dict:
|
||||
w, h, n = struct.unpack_from("<HHI", blob, 12)
|
||||
return {"format": blob[3], "width": w, "height": h, "length": n}
|
||||
|
||||
|
||||
def to_rgb565(pixels_rgb, width: int, height: int) -> bytes:
|
||||
"""pixels_rgb: callable (x, y) -> (r, g, b)."""
|
||||
out = bytearray(width * height * 2)
|
||||
for x in range(width):
|
||||
for y in range(height):
|
||||
r, g, b = pixels_rgb(x, y)[:3]
|
||||
v = (r >> 3) << 11 | (g >> 2) << 5 | (b >> 3)
|
||||
struct.pack_into("<H", out, 2 * (x * height + (height - 1 - y)), v)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def make_picture(rgb565: bytes, width: int, height: int) -> bytes:
|
||||
return I_MAGIC + b"\x00" + struct.pack("<IIHHII", 0, 24, width, height, len(rgb565), 0) + rgb565
|
||||
|
||||
|
||||
def from_image_file(data: bytes):
|
||||
"""Image file bytes (png/jpg/bmp) -> (N.i blob, N.is blob). Needs Pillow."""
|
||||
from PIL import Image
|
||||
img = Image.open(io.BytesIO(data))
|
||||
ftype = (img.format or "png").lower()[:3]
|
||||
rgb = img.convert("RGB")
|
||||
px = rgb.load()
|
||||
w, h = rgb.size
|
||||
return make_picture(to_rgb565(lambda x, y: px[x, y], w, h), w, h), make_source(data, w, h, ftype)
|
||||
|
||||
|
||||
def to_image(blob: bytes):
|
||||
"""Decode a format-0 ``N.i`` to a Pillow image."""
|
||||
from PIL import Image
|
||||
d = info(blob)
|
||||
if d["format"] != 0:
|
||||
raise NotImplementedError("picture format %d (Intelligent compressed) not supported yet" % d["format"])
|
||||
w, h = d["width"], d["height"]
|
||||
img = Image.new("RGB", (w, h))
|
||||
px = img.load()
|
||||
for x in range(w):
|
||||
for y in range(h):
|
||||
v, = struct.unpack_from("<H", blob, 24 + 2 * (x * h + (h - 1 - y)))
|
||||
r, g, b = v >> 11, (v >> 5) & 63, v & 31
|
||||
px[x, y] = (r << 3 | r >> 2, g << 2 | g >> 4, b << 3 | b >> 2)
|
||||
return img
|
||||
@@ -0,0 +1,306 @@
|
||||
"""Decode a .HMI into a readable, diffable folder -- and encode such a folder back.
|
||||
|
||||
Folder layout::
|
||||
|
||||
manifest.json entry order, model info, which file holds what
|
||||
Program.s the project's start-up script (plain text)
|
||||
main.HMI.json the project header, parsed where understood (+ raw hex)
|
||||
pages/<N>_<name>.json one file per page: header fields + components
|
||||
resources/<entry> every other entry (pictures, fonts, ...) as raw bytes
|
||||
|
||||
Page JSON::
|
||||
|
||||
{"file": "1.pa", "name": "main", "password": 0, "locked": 0, ...,
|
||||
"components": [
|
||||
{"att": [["type", "u8", 121], ["objname", "str", "main"], ...],
|
||||
"events": {"codesdown": ["page 2"], ...},
|
||||
"order": ["att", "codesload", ...]} # group order, for exact round trips
|
||||
]}
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import struct
|
||||
|
||||
from . import checksum, enums
|
||||
from .container import HMIFile, build
|
||||
from .page import Attr, Component, Group, Page
|
||||
|
||||
MODELS = {
|
||||
# model id (main.HMI offset 16) -> (part number, description). Values observed or taken
|
||||
# from public lists of Nextion models; extend as needed.
|
||||
0xB23BC018: ("NX4832T035_011", 'Nextion 3.5" Basic 480x320'),
|
||||
}
|
||||
|
||||
|
||||
def _safe(name: str) -> str:
|
||||
return "".join(ch if ch.isalnum() or ch in "-_." else "_" for ch in name)
|
||||
|
||||
|
||||
def parse_main(blob: bytes) -> dict:
|
||||
d = {"crc_ok": checksum.main_crc(blob) == struct.unpack_from("<I", blob, 0)[0],
|
||||
"model_id": "0x%08X" % struct.unpack_from("<I", blob, 16)[0]}
|
||||
mid = struct.unpack_from("<I", blob, 16)[0]
|
||||
if mid in MODELS:
|
||||
d["model"], d["model_desc"] = MODELS[mid]
|
||||
# resource list: header size at +4 (= list start), count at +28, entries of type[8] + name[8]
|
||||
start, = struct.unpack_from("<I", blob, 4)
|
||||
count, = struct.unpack_from("<I", blob, 28)
|
||||
res = []
|
||||
for i in range(count):
|
||||
o = start + 16 * i
|
||||
res.append([blob[o:o + 8].rstrip(b"\0").decode("latin-1"), blob[o + 8:o + 16].rstrip(b"\0").decode("latin-1")])
|
||||
d["resources"] = res
|
||||
d["raw_hex"] = blob.hex()
|
||||
return d
|
||||
|
||||
|
||||
def component_to_json(c: Component, encoding: str, readable: bool = True) -> dict:
|
||||
out = {"order": [g.name for g in c.groups]}
|
||||
events = {}
|
||||
ctype = c.get("type")
|
||||
for g in c.groups:
|
||||
if g.name == "att":
|
||||
out["att"] = []
|
||||
for a in g.records:
|
||||
kind, value = a.decoded(encoding)
|
||||
if readable:
|
||||
value = enums.to_label(ctype, a.name, kind, value)
|
||||
out["att"].append([a.name, kind, value])
|
||||
else:
|
||||
events[g.name] = [r.decode(encoding) for r in g.records]
|
||||
out["events"] = events
|
||||
if c.table_extra:
|
||||
out["table_extra"] = c.table_extra
|
||||
if c.trailing:
|
||||
out["trailing_hex"] = c.trailing.hex()
|
||||
return out
|
||||
|
||||
|
||||
def component_from_json(d: dict, encoding: str) -> Component:
|
||||
groups = []
|
||||
ctype = next((v for n, k, v in d.get("att", []) if n == "type"), None)
|
||||
for gname in d.get("order", ["att"] + list(d.get("events", {}))):
|
||||
if gname == "att":
|
||||
groups.append(Group("att", [Attr.encode(n, k, enums.from_label(ctype, n, k, v), encoding)
|
||||
for n, k, v in d["att"]]))
|
||||
else:
|
||||
groups.append(Group(gname, [ln.encode(encoding) for ln in d["events"][gname]]))
|
||||
return Component(groups, d.get("table_extra", 0), bytes.fromhex(d.get("trailing_hex", "")))
|
||||
|
||||
|
||||
def page_to_json(entry_name: str, p: Page, encoding: str, readable: bool = True) -> dict:
|
||||
return {"file": entry_name, "name": p.name, "password": p.password, "locked": p.locked,
|
||||
"b21": p.b21, "version": p.version, "b23": p.b23, "reserved_hex": p.reserved.hex(),
|
||||
"components": [component_to_json(c, encoding, readable) for c in p.components]}
|
||||
|
||||
|
||||
def page_from_json(d: dict, encoding: str) -> Page:
|
||||
return Page(d["name"], [component_from_json(c, encoding) for c in d["components"]],
|
||||
d.get("password", 0), d.get("locked", 0), d.get("b21", 0x4F), d.get("version", 0x21),
|
||||
d.get("b23", 0), bytes.fromhex(d.get("reserved_hex", "00" * 16)))
|
||||
|
||||
|
||||
def decode(hmi_path: str, out_dir: str, encoding: str = "latin-1", readable: bool = True) -> dict:
|
||||
h = HMIFile.load(hmi_path)
|
||||
os.makedirs(os.path.join(out_dir, "pages"), exist_ok=True)
|
||||
os.makedirs(os.path.join(out_dir, "resources"), exist_ok=True)
|
||||
manifest = {"format": "nxhmi-folder-1", "encoding": encoding, "entries": []}
|
||||
for e in h.live():
|
||||
blob = h.read(e.name)
|
||||
item = {"name": e.name}
|
||||
if e.name.endswith(".pa"):
|
||||
p = Page.parse(blob)
|
||||
fn = "pages/%s_%s.json" % (_safe(e.name[:-3]), _safe(p.name))
|
||||
with open(os.path.join(out_dir, fn), "w", encoding="utf-8") as f:
|
||||
json.dump(page_to_json(e.name, p, encoding, readable), f, indent=1, ensure_ascii=False)
|
||||
item["page"] = fn
|
||||
elif e.name == "Program.s":
|
||||
with open(os.path.join(out_dir, "Program.s"), "wb") as f:
|
||||
f.write(blob)
|
||||
item["file"] = "Program.s"
|
||||
elif e.name == "main.HMI":
|
||||
info = parse_main(blob)
|
||||
with open(os.path.join(out_dir, "main.HMI.json"), "w", encoding="utf-8") as f:
|
||||
json.dump(info, f, indent=1)
|
||||
item["main"] = "main.HMI.json"
|
||||
manifest["model"] = info.get("model", info["model_id"])
|
||||
else:
|
||||
fn = "resources/" + _safe(e.name)
|
||||
with open(os.path.join(out_dir, fn), "wb") as f:
|
||||
f.write(blob)
|
||||
item["file"] = fn
|
||||
_write_preview(out_dir, e.name, blob)
|
||||
manifest["entries"].append(item)
|
||||
with open(os.path.join(out_dir, "manifest.json"), "w", encoding="utf-8") as f:
|
||||
json.dump(manifest, f, indent=1)
|
||||
return manifest
|
||||
|
||||
|
||||
def encode(folder: str, hmi_path: str) -> None:
|
||||
with open(os.path.join(folder, "manifest.json"), encoding="utf-8") as f:
|
||||
manifest = json.load(f)
|
||||
enc = manifest.get("encoding", "latin-1")
|
||||
items = []
|
||||
for it in manifest["entries"]:
|
||||
if "page" in it:
|
||||
with open(os.path.join(folder, it["page"]), encoding="utf-8") as f:
|
||||
items.append((it["name"], page_from_json(json.load(f), enc).pack()))
|
||||
elif "main" in it:
|
||||
with open(os.path.join(folder, it["main"]), encoding="utf-8") as f:
|
||||
blob = bytearray(bytes.fromhex(json.load(f)["raw_hex"]))
|
||||
struct.pack_into("<I", blob, 0, checksum.main_crc(bytes(blob)))
|
||||
items.append((it["name"], bytes(blob)))
|
||||
else:
|
||||
with open(os.path.join(folder, it["file"]), "rb") as f:
|
||||
items.append((it["name"], f.read()))
|
||||
build(items).save(hmi_path)
|
||||
|
||||
|
||||
def main_add_resource(main: bytes, rtype: str, name: str) -> bytes:
|
||||
"""Return main.HMI with one more resource-list entry (e.g. "pa", "6.pa") and a new checksum."""
|
||||
start, = struct.unpack_from("<I", main, 4)
|
||||
count, = struct.unpack_from("<I", main, 28)
|
||||
b = bytearray(main[:start + 16 * count])
|
||||
b += rtype.encode("latin-1")[:8].ljust(8, b"\0") + name.encode("latin-1")[:8].ljust(8, b"\0")
|
||||
struct.pack_into("<I", b, 28, count + 1)
|
||||
struct.pack_into("<I", b, 0, checksum.main_crc(bytes(b)))
|
||||
return bytes(b)
|
||||
|
||||
|
||||
def add_page(h: HMIFile, name: str, **attrs) -> Page:
|
||||
"""Add a new empty page to an opened project (next free N.pa) and register it in main.HMI."""
|
||||
from .components import new_page
|
||||
used = {Page.parse(h.read(e.name)).name for e in h.live() if e.name.endswith(".pa")}
|
||||
if name in used:
|
||||
raise ValueError("page %r exists" % name)
|
||||
n = 0
|
||||
while h.find("%d.pa" % n):
|
||||
n += 1
|
||||
p = new_page(name, **attrs)
|
||||
h.write("%d.pa" % n, p.pack())
|
||||
h.write("main.HMI", main_add_resource(h.read("main.HMI"), "pa", "%d.pa" % n))
|
||||
return p
|
||||
|
||||
|
||||
def main_insert_resource(main: bytes, rtype: str, name: str) -> bytes:
|
||||
"""Like main_add_resource, but keeps entries grouped by type (the Editor lists i, zi, pa)."""
|
||||
start, = struct.unpack_from("<I", main, 4)
|
||||
count, = struct.unpack_from("<I", main, 28)
|
||||
ents = [main[start + 16 * i:start + 16 * i + 16] for i in range(count)]
|
||||
new = rtype.encode("latin-1")[:8].ljust(8, bytes(1)) + name.encode("latin-1")[:8].ljust(8, bytes(1))
|
||||
pos = count
|
||||
for i in range(count - 1, -1, -1):
|
||||
if ents[i][:8] == new[:8]:
|
||||
pos = i + 1
|
||||
break
|
||||
else:
|
||||
order = ["i", "zi", "pa"]
|
||||
if rtype in order:
|
||||
later = order[order.index(rtype) + 1:]
|
||||
for i, e in enumerate(ents):
|
||||
if e[:8].rstrip(bytes(1)).decode("latin-1") in later:
|
||||
pos = i
|
||||
break
|
||||
ents.insert(pos, new)
|
||||
b = bytearray(main[:start]) + b"".join(ents)
|
||||
struct.pack_into("<I", b, 28, count + 1)
|
||||
struct.pack_into("<I", b, 0, checksum.main_crc(bytes(b)))
|
||||
return bytes(b)
|
||||
|
||||
|
||||
def add_picture(h: HMIFile, image_file: bytes) -> int:
|
||||
"""Add a picture (png/jpg/bmp bytes) to the project; returns its picture id. Basic series only."""
|
||||
from . import pictures
|
||||
n = 0
|
||||
while h.find("%d.i" % n):
|
||||
n += 1
|
||||
pic, src = pictures.from_image_file(image_file)
|
||||
h.write("%d.is" % n, src)
|
||||
h.write("%d.i" % n, pic)
|
||||
h.write("main.HMI", main_insert_resource(h.read("main.HMI"), "i", "%d.i" % n))
|
||||
return n
|
||||
|
||||
|
||||
def _write_preview(out_dir: str, name: str, blob: bytes) -> None:
|
||||
"""Human-readable companions of binary resources (never read back by encode)."""
|
||||
from . import fonts, pictures
|
||||
try:
|
||||
if name.endswith(".is"):
|
||||
info = pictures.source_info(blob)
|
||||
with open(os.path.join(out_dir, "resources", _safe(name) + "." + (info["type"] or "bin")), "wb") as f:
|
||||
f.write(pictures.source_file(blob))
|
||||
elif name.endswith(".zi"):
|
||||
font = fonts.Font.parse(blob)
|
||||
lines = ["font %r %dx%d encoding %d chars 0x%02X-0x%02X" % (font.name, font.width, font.height,
|
||||
font.encoding, font.first, font.last)]
|
||||
for g in font.glyphs:
|
||||
lines.append("")
|
||||
lines.append("char 0x%02X %r width %d" % (g.code, chr(g.code), g.width))
|
||||
lines += ["".join("#" if v else "." for v in row) for row in g.pixels]
|
||||
with open(os.path.join(out_dir, "resources", _safe(name) + ".txt"), "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(lines) + "\n")
|
||||
except (ValueError, NotImplementedError, struct.error):
|
||||
pass
|
||||
|
||||
|
||||
def add_font(h: HMIFile, font) -> int:
|
||||
"""Add a fonts.Font to the project; returns its font id."""
|
||||
n = 0
|
||||
while h.find("%d.zi" % n):
|
||||
n += 1
|
||||
h.write("%d.zi" % n, font.pack())
|
||||
h.write("main.HMI", main_insert_resource(h.read("main.HMI"), "zi", "%d.zi" % n))
|
||||
return n
|
||||
|
||||
|
||||
DEFAULT_PROGRAM = (
|
||||
"//Program.s runs once at power-on, before the first page is shown.\r\n"
|
||||
"//Global variables can be declared here: int sys0=0\r\n"
|
||||
"baud=115200\r\n"
|
||||
"page 0\r\n"
|
||||
)
|
||||
|
||||
|
||||
def make_main(model: str, resources: list, encoding: str = "iso-8859-1") -> bytes:
|
||||
"""Build a main.HMI project header from scratch.
|
||||
|
||||
Field values follow Nextion Editor 1.68 output (see docs/FORMAT.md); ``resources`` is a list of
|
||||
(type, name) such as ("pa", "0.pa").
|
||||
"""
|
||||
from . import models
|
||||
mid, series, _, _ = models.lookup(model)
|
||||
b = bytearray(0x60)
|
||||
struct.pack_into("<I", b, 4, 0x60) # header size / resource list start
|
||||
b[8:12] = bytes([0x01, 0x44, 0x21, series])
|
||||
b[12:16] = bytes([models.ENCODINGS[encoding], 0x03, 0x4F, 0x00])
|
||||
struct.pack_into("<I", b, 16, mid)
|
||||
struct.pack_into("<I", b, 24, 0x60)
|
||||
struct.pack_into("<I", b, 28, len(resources))
|
||||
struct.pack_into("<I", b, 36, 2)
|
||||
b[0x41] = 3 # Editor 1.68 writes 3 here (0 in 2019 files)
|
||||
for rtype, name in resources:
|
||||
b += rtype.encode("latin-1")[:8].ljust(8, bytes(1)) + name.encode("latin-1")[:8].ljust(8, bytes(1))
|
||||
struct.pack_into("<I", b, 0, checksum.main_crc(bytes(b)))
|
||||
return bytes(b)
|
||||
|
||||
|
||||
def new_project(model: str = "NX4832T035_011", first_page: str = "page0", program: str = DEFAULT_PROGRAM) -> HMIFile:
|
||||
"""A new, empty project with one page -- no Nextion files needed."""
|
||||
from . import models
|
||||
from .components import new_page
|
||||
_, _, w, h = models.lookup(model)
|
||||
page = new_page(first_page, w=w, h=h)
|
||||
items = [("main.HMI", make_main(model, [("pa", "0.pa")])),
|
||||
("Program.s", program.encode("latin-1")),
|
||||
("0.pa", page.pack())]
|
||||
return build(items)
|
||||
|
||||
|
||||
def project_size(h: HMIFile):
|
||||
"""(width, height) of the project's display, from main.HMI."""
|
||||
from . import models
|
||||
mid = struct.unpack_from("<I", h.read("main.HMI"), 16)[0]
|
||||
name = models.BY_ID.get(mid)
|
||||
return models.MODELS[name][2:4] if name else (480, 320)
|
||||
@@ -0,0 +1,362 @@
|
||||
"""Render pages to images, the way Nextion Editor draws them on its canvas (needs Pillow).
|
||||
|
||||
Usage::
|
||||
|
||||
from nxhmi.render import Renderer
|
||||
r = Renderer(HMIFile.load("project.HMI"))
|
||||
r.render("main").save("main.png")
|
||||
|
||||
Covered: page background (colour / picture), picture, crop, text, scrolling text (static), number,
|
||||
xfloat, button, dual-state button, slider, progress bar, checkbox, radio, gauge, waveform (frame +
|
||||
grid), QR code (placeholder pattern). Invisible components (timer, variable, hotspot, touch cap)
|
||||
draw nothing. See docs/RENDER.md for how close each one is to the Editor.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
from .container import HMIFile
|
||||
from .fonts import Font
|
||||
from .page import Component, Page
|
||||
from . import pictures
|
||||
|
||||
|
||||
def rgb(v: int):
|
||||
r, g, b = v >> 11, (v >> 5) & 63, v & 31
|
||||
return (r << 3 | r >> 2, g << 2 | g >> 4, b << 3 | b >> 2)
|
||||
|
||||
|
||||
class Renderer:
|
||||
def __init__(self, hmi: HMIFile):
|
||||
from PIL import Image # noqa: F401 (fail early if Pillow is missing)
|
||||
self.h = hmi
|
||||
self._pics = {}
|
||||
self._fonts = {}
|
||||
self.pages = {}
|
||||
for e in hmi.live():
|
||||
if e.name.endswith(".pa"):
|
||||
p = Page.parse(hmi.read(e.name))
|
||||
self.pages[p.name] = p
|
||||
self.pages[int(e.name[:-3])] = p
|
||||
|
||||
# ------------------------------------------------------------------ resources
|
||||
def pic(self, n: int):
|
||||
if n not in self._pics:
|
||||
try:
|
||||
self._pics[n] = pictures.to_image(self.h.read("%d.i" % n))
|
||||
except (KeyError, NotImplementedError):
|
||||
self._pics[n] = None
|
||||
return self._pics[n]
|
||||
|
||||
def font(self, n: int):
|
||||
if n not in self._fonts:
|
||||
try:
|
||||
self._fonts[n] = Font.parse(self.h.read("%d.zi" % n))
|
||||
except (KeyError, ValueError):
|
||||
self._fonts[n] = None
|
||||
return self._fonts[n]
|
||||
|
||||
# ------------------------------------------------------------------ page
|
||||
def render(self, page) -> "Image":
|
||||
from PIL import Image
|
||||
p = self.pages[page]
|
||||
pc = p.components[0]
|
||||
w, h = pc.get("w") or 480, pc.get("h") or 320
|
||||
img = Image.new("RGB", (w, h), (255, 255, 255))
|
||||
sta = pc.get("sta")
|
||||
if sta == 1:
|
||||
img.paste(rgb(pc.get("bco")), (0, 0, w, h))
|
||||
elif sta == 2:
|
||||
pic = self.pic(pc.get("pic"))
|
||||
if pic:
|
||||
self._paste(img, pic, 0, 0, w, h, 0, 0)
|
||||
for c in p.components[1:]:
|
||||
self.draw(img, c)
|
||||
return img
|
||||
|
||||
# ------------------------------------------------------------------ components
|
||||
def draw(self, img, c: Component):
|
||||
t = c.get("type")
|
||||
fn = {116: self.text, 55: self.text, 98: self.text, 53: self.dual, 54: self.number, 59: self.xfloat,
|
||||
112: self.picture, 113: self.crop, 1: self.slider, 106: self.progress, 56: self.checkbox,
|
||||
57: self.radio, 122: self.gauge, 0: self.waveform, 58: self.qrcode}.get(t)
|
||||
if fn:
|
||||
fn(img, c)
|
||||
|
||||
@staticmethod
|
||||
def _paste(img, src, sx, sy, w, h, dx, dy):
|
||||
"""Paste src[sx:sx+w, sy:sy+h] at (dx, dy), clipped to src's real size (no black padding)."""
|
||||
w = min(w, src.width - sx)
|
||||
h = min(h, src.height - sy)
|
||||
if w > 0 and h > 0:
|
||||
img.paste(src.crop((sx, sy, sx + w, sy + h)), (dx, dy))
|
||||
|
||||
def _box(self, c):
|
||||
x, y, w, h = c.get("x"), c.get("y"), c.get("w"), c.get("h")
|
||||
return x, y, w, h
|
||||
|
||||
def _background(self, img, c, x, y, w, h):
|
||||
sta = c.get("sta")
|
||||
if sta == 0: # crop image: same area of picture picc
|
||||
src = self.pic(c.get("picc"))
|
||||
if src:
|
||||
self._paste(img, src, x, y, w, h, x, y)
|
||||
elif sta == 1:
|
||||
img.paste(rgb(c.get("bco")), (x, y, x + w, y + h))
|
||||
elif sta == 2:
|
||||
src = self.pic(c.get("pic"))
|
||||
if src:
|
||||
self._paste(img, src, 0, 0, w, h, x, y)
|
||||
|
||||
def _border(self, img, c, x, y, w, h, override=None):
|
||||
from PIL import ImageDraw
|
||||
d = ImageDraw.Draw(img)
|
||||
style = c.get("style") if override is None else override
|
||||
if c.get("sta") in (0, 2) and c.get("type") in (98, 53):
|
||||
return # picture-skinned buttons have no frame
|
||||
if style == 1: # border
|
||||
bw, bc = c.get("borderw") or 0, rgb(c.get("borderc") or 0)
|
||||
for i in range(bw):
|
||||
d.rectangle((x + i, y + i, x + w - 1 - i, y + h - 1 - i), outline=bc)
|
||||
elif style in (2, 3, 4): # 3D down / up / auto(=up when released)
|
||||
light, dark = (230, 226, 230), (65, 68, 65) # measured in Editor 1.68
|
||||
if style == 2:
|
||||
light, dark = dark, light
|
||||
d.line((x, y, x + w - 1, y), fill=light); d.line((x, y, x, y + h - 1), fill=light)
|
||||
d.line((x, y + h - 1, x + w - 1, y + h - 1), fill=dark); d.line((x + w - 1, y, x + w - 1, y + h - 1), fill=dark)
|
||||
|
||||
def _text(self, img, c, s, x, y, w, h, color):
|
||||
font = self.font(c.get("font") or 0)
|
||||
if font is None or not s:
|
||||
return
|
||||
spax, spay = c.get("spax") or 0, c.get("spay") or 0
|
||||
xcen, ycen = c.get("xcen"), c.get("ycen")
|
||||
wrap = c.get("isbr")
|
||||
glyphs = {g.code: g for g in font.glyphs}
|
||||
|
||||
def gw(ch):
|
||||
g = glyphs.get(ord(ch))
|
||||
return (g.width if g else font.width) + spax
|
||||
|
||||
lines = []
|
||||
for para in s.replace("\r\n", "\n").split("\n"):
|
||||
cur = ""
|
||||
for ch in para:
|
||||
if wrap and cur and sum(gw(k) for k in cur + ch) - spax > w:
|
||||
lines.append(cur); cur = ""
|
||||
cur += ch
|
||||
lines.append(cur)
|
||||
line_h = font.height + spay
|
||||
total_h = len(lines) * line_h - spay
|
||||
if ycen == 1:
|
||||
ty = y + max(0, (h - total_h) // 2) # never starts above the box
|
||||
elif ycen == 2:
|
||||
ty = y + max(0, h - total_h)
|
||||
else:
|
||||
ty = y
|
||||
px = img.load()
|
||||
W, H = img.size
|
||||
# the Editor aligns the text *block* (widest line); lines are left-aligned inside it
|
||||
block_w = max((sum(gw(k) for k in ln) - (spax if ln else 0)) for ln in lines)
|
||||
for ln in lines:
|
||||
lw = block_w
|
||||
if xcen == 1:
|
||||
tx = x + max(0, (w - lw) // 2)
|
||||
elif xcen == 2:
|
||||
tx = x + max(0, w - lw)
|
||||
else:
|
||||
tx = x
|
||||
for ch in ln:
|
||||
g = glyphs.get(ord(ch))
|
||||
if g:
|
||||
for gy, row in enumerate(g.pixels):
|
||||
yy = ty + gy
|
||||
if yy < y or yy >= y + h or yy >= H:
|
||||
continue
|
||||
for gx, v in enumerate(row):
|
||||
xx = tx + gx
|
||||
if v and x <= xx < x + w and 0 <= xx < W and yy >= 0:
|
||||
px[xx, yy] = color
|
||||
tx += gw(ch)
|
||||
ty += line_h
|
||||
|
||||
def dual(self, img, c):
|
||||
"""Dual-state button: val=1 shows the second skin (bco2 / pic2 / picc2) and pco2."""
|
||||
x, y, w, h = self._box(c)
|
||||
on = bool(c.get("val"))
|
||||
sta = c.get("sta")
|
||||
if sta == 1:
|
||||
img.paste(rgb((c.get("bco2") if on else c.get("bco")) or 0), (x, y, x + w, y + h))
|
||||
elif sta == 2:
|
||||
src = self.pic(c.get("pic2") if on else c.get("pic"))
|
||||
if src:
|
||||
self._paste(img, src, 0, 0, w, h, x, y)
|
||||
elif sta == 0:
|
||||
src = self.pic(c.get("picc2") if on else c.get("picc"))
|
||||
if src:
|
||||
self._paste(img, src, x, y, w, h, x, y)
|
||||
if on and c.get("style") == 4 and sta == 1:
|
||||
self._border(img, c, x, y, w, h, override=2) # "on" looks pressed: 3D down
|
||||
else:
|
||||
self._border(img, c, x, y, w, h)
|
||||
self._text(img, c, c.get("txt") or "", *self._inner(c, x, y, w, h),
|
||||
rgb((c.get("pco2") if on else c.get("pco")) or 0))
|
||||
|
||||
def _inner(self, c, x, y, w, h):
|
||||
"""Text area inside the border."""
|
||||
style = c.get("style")
|
||||
b = (c.get("borderw") or 0) if style == 1 else (1 if style in (2, 3, 4) else 0)
|
||||
return x + b, y + b, w - 2 * b, h - 2 * b
|
||||
|
||||
def text(self, img, c):
|
||||
x, y, w, h = self._box(c)
|
||||
self._background(img, c, x, y, w, h)
|
||||
self._border(img, c, x, y, w, h)
|
||||
self._text(img, c, c.get("txt") or "", *self._inner(c, x, y, w, h), rgb(c.get("pco") or 0))
|
||||
|
||||
def number(self, img, c):
|
||||
v = c.get("val") or 0
|
||||
if v >= 0x80000000:
|
||||
v -= 1 << 32
|
||||
fmt, length = c.get("format"), c.get("lenth") or 0
|
||||
s = ("%X" % (v & 0xFFFFFFFF)) if fmt == 2 else ("{:,}".format(v) if fmt == 1 else str(v))
|
||||
if length and fmt != 1:
|
||||
s = s.zfill(length)[-length:]
|
||||
x, y, w, h = self._box(c)
|
||||
self._background(img, c, x, y, w, h)
|
||||
self._border(img, c, x, y, w, h)
|
||||
self._text(img, c, s, *self._inner(c, x, y, w, h), rgb(c.get("pco") or 0))
|
||||
|
||||
def xfloat(self, img, c):
|
||||
v = c.get("val") or 0
|
||||
if v >= 0x80000000:
|
||||
v -= 1 << 32
|
||||
ints, decs = c.get("vvs0") or 0, c.get("vvs1") or 0
|
||||
s = str(abs(v)).zfill(decs + 1)
|
||||
s = (s[:-decs] + "." + s[-decs:]) if decs else s
|
||||
if ints:
|
||||
ip, _, dp = s.partition(".")
|
||||
s = ip.zfill(ints)[-ints:] + ("." + dp if dp else "")
|
||||
s = ("-" if v < 0 else "") + s
|
||||
x, y, w, h = self._box(c)
|
||||
self._background(img, c, x, y, w, h)
|
||||
self._border(img, c, x, y, w, h)
|
||||
self._text(img, c, s, *self._inner(c, x, y, w, h), rgb(c.get("pco") or 0))
|
||||
|
||||
def picture(self, img, c):
|
||||
src = self.pic(c.get("pic"))
|
||||
if src:
|
||||
x, y, w, h = self._box(c)
|
||||
self._paste(img, src, 0, 0, w, h, x, y)
|
||||
|
||||
def crop(self, img, c):
|
||||
src = self.pic(c.get("picc"))
|
||||
if src:
|
||||
x, y, w, h = self._box(c)
|
||||
self._paste(img, src, x, y, w, h, x, y)
|
||||
|
||||
def slider(self, img, c):
|
||||
from PIL import ImageDraw
|
||||
x, y, w, h = self._box(c)
|
||||
self._background(img, c, x, y, w, h)
|
||||
d = ImageDraw.Draw(img)
|
||||
vmin, vmax, val = c.get("minval") or 0, c.get("maxval") or 100, c.get("val") or 0
|
||||
frac = 0 if vmax == vmin else (val - vmin) / (vmax - vmin)
|
||||
vertical = c.get("mode") == 1
|
||||
cw = c.get("wid"); ch = c.get("hig")
|
||||
if c.get("psta") == 1: # picture cursor (pic2) at its own size
|
||||
knob = self.pic(c.get("pic2"))
|
||||
if knob:
|
||||
kw, kh = knob.size
|
||||
if vertical:
|
||||
ky = y + h - kh - int(frac * (h - kh))
|
||||
img.paste(knob, (x + (w - kw) // 2, ky))
|
||||
else:
|
||||
kx = x + int(frac * (w - kw))
|
||||
img.paste(knob, (kx, y + (h - kh) // 2))
|
||||
return
|
||||
# "auto" (255) cursor = a square as thick as the slider
|
||||
if vertical:
|
||||
cw = w if cw in (None, 255) else cw
|
||||
ch = w if ch in (None, 255) else ch
|
||||
cy = y + h - ch - int(frac * (h - ch)) # truncates, like the Editor
|
||||
d.rectangle((x + (w - cw) // 2, cy, x + (w - cw) // 2 + cw - 1, cy + ch - 1), fill=rgb(c.get("pco") or 0))
|
||||
else:
|
||||
ch = h if ch in (None, 255) else ch
|
||||
cw = h if cw in (None, 255) else cw
|
||||
cx = x + int(frac * (w - cw)) # truncates, like the Editor
|
||||
d.rectangle((cx, y + (h - ch) // 2, cx + cw - 1, y + (h - ch) // 2 + ch - 1), fill=rgb(c.get("pco") or 0))
|
||||
|
||||
def progress(self, img, c):
|
||||
from PIL import ImageDraw
|
||||
x, y, w, h = self._box(c)
|
||||
d = ImageDraw.Draw(img)
|
||||
val = max(0, min(100, c.get("val") or 0))
|
||||
if c.get("sta") == 1: # picture mode: bpic background, ppic foreground
|
||||
bg, fg = self.pic(c.get("bpic")), self.pic(c.get("ppic"))
|
||||
if bg:
|
||||
self._paste(img, bg, 0, 0, w, h, x, y)
|
||||
if fg:
|
||||
if c.get("dez") == 1:
|
||||
fh = h * val // 100
|
||||
if fh:
|
||||
self._paste(img, fg, 0, h - fh, w, fh, x, y + h - fh)
|
||||
else:
|
||||
fw = w * val // 100
|
||||
if fw:
|
||||
self._paste(img, fg, 0, 0, fw, h, x, y)
|
||||
return
|
||||
d.rectangle((x, y, x + w - 1, y + h - 1), fill=rgb(c.get("bco") or 0))
|
||||
if c.get("dez") == 1:
|
||||
fh = h * val // 100
|
||||
if fh:
|
||||
d.rectangle((x, y + h - fh, x + w - 1, y + h - 1), fill=rgb(c.get("pco") or 0))
|
||||
else:
|
||||
fw = w * val // 100
|
||||
if fw:
|
||||
d.rectangle((x, y, x + fw - 1, y + h - 1), fill=rgb(c.get("pco") or 0))
|
||||
|
||||
def checkbox(self, img, c):
|
||||
from PIL import ImageDraw
|
||||
x, y, w, h = self._box(c)
|
||||
d = ImageDraw.Draw(img)
|
||||
d.rectangle((x, y, x + w - 1, y + h - 1), fill=rgb(c.get("bco") or 0))
|
||||
self._border(img, c, x, y, w, h)
|
||||
if c.get("val"): # filled square, half the size, centred
|
||||
d.rectangle((x + w // 4, y + h // 4, x + 3 * w // 4 - 1, y + 3 * h // 4 - 1), fill=rgb(c.get("pco") or 0))
|
||||
|
||||
def radio(self, img, c):
|
||||
from PIL import ImageDraw
|
||||
x, y, w, h = self._box(c)
|
||||
d = ImageDraw.Draw(img)
|
||||
d.ellipse((x, y, x + w - 2, y + h - 2), fill=rgb(c.get("bco") or 0), outline=(65, 68, 65))
|
||||
if c.get("val"):
|
||||
d.ellipse((x + w // 4, y + h // 4, x + 3 * w // 4 - 2, y + 3 * h // 4 - 2), fill=rgb(c.get("pco") or 0))
|
||||
|
||||
def gauge(self, img, c):
|
||||
from PIL import ImageDraw
|
||||
x, y, w, h = self._box(c)
|
||||
self._background(img, c, x, y, w, h)
|
||||
d = ImageDraw.Draw(img)
|
||||
r = min(w, h) // 2 - 1
|
||||
cx, cy = x + w // 2, y + h // 2
|
||||
a = math.radians(c.get("val") or 0)
|
||||
d.line((cx, cy, cx - int(r * math.cos(a)), cy - int(r * math.sin(a))), fill=rgb(c.get("pco") or 0),
|
||||
width=max(1, c.get("wid") or 1))
|
||||
|
||||
def waveform(self, img, c):
|
||||
from PIL import ImageDraw
|
||||
x, y, w, h = self._box(c)
|
||||
self._background(img, c, x, y, w, h)
|
||||
d = ImageDraw.Draw(img)
|
||||
gw, gh, gc = c.get("gdw") or 0, c.get("gdh") or 0, rgb(c.get("gdc") or 0)
|
||||
if gw:
|
||||
for xx in range(x, x + w, gw):
|
||||
d.line((xx, y, xx, y + h - 1), fill=gc)
|
||||
if gh: # horizontal lines count from the bottom
|
||||
for yy in range(y + h - 1, y - 1, -gh):
|
||||
d.line((x, yy, x + w - 1, yy), fill=gc)
|
||||
|
||||
def qrcode(self, img, c):
|
||||
x, y, w, h = self._box(c)
|
||||
img.paste(rgb(c.get("bco") or 0xFFFF), (x, y, x + w, y + h))
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,54 @@
|
||||
"""Nextion .tft (compiled firmware) -- research-stage helpers. See docs/NOTES.md.
|
||||
|
||||
Only what is verified is implemented here:
|
||||
|
||||
* the obfuscated layout table at 0xC8..0x113 is XOR 0xEBAB2932 per 32-bit word;
|
||||
* the trailer (last 4 bytes, LE) is a word-per-byte CRC whose stream ends at the trailer -- so
|
||||
for edits that keep the file length, the trailer can be updated by linearity
|
||||
(:func:`patch_trailer`). Building a .tft from scratch is not possible yet: the trailer's start
|
||||
offset / seed are unknown, and every .tft embeds Nextion's own firmware files, which this
|
||||
project does not and must not distribute.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
|
||||
from .checksum import _feed_byte_as_word, _feed_word
|
||||
|
||||
LAYOUT_KEY = 0xEBAB2932
|
||||
LAYOUT_START, LAYOUT_END = 0xC8, 0x114
|
||||
|
||||
|
||||
def layout_table(tft: bytes) -> list[int]:
|
||||
"""De-obfuscated words of the layout table (offsets/sizes/counts)."""
|
||||
return [struct.unpack_from("<I", tft, o)[0] ^ LAYOUT_KEY for o in range(LAYOUT_START, LAYOUT_END, 4)]
|
||||
|
||||
|
||||
def header_info(tft: bytes) -> dict:
|
||||
return {
|
||||
"width": struct.unpack_from("<H", tft, 0x0C)[0],
|
||||
"height": struct.unpack_from("<H", tft, 0x0E)[0],
|
||||
"model_id": "0x%08X" % struct.unpack_from("<I", tft, 0x2E)[0],
|
||||
"file_size": struct.unpack_from("<I", tft, 0x3C)[0],
|
||||
"layout": layout_table(tft),
|
||||
}
|
||||
|
||||
|
||||
def _zero_words(n: int, c: int) -> int:
|
||||
for _ in range(n):
|
||||
c = _feed_word(c, 0)
|
||||
return c
|
||||
|
||||
|
||||
def patch_trailer(old: bytes, new: bytes) -> bytes:
|
||||
"""Return ``new`` with its trailer CRC updated, given the Editor-made ``old`` of the same length."""
|
||||
if len(old) != len(new):
|
||||
raise ValueError("only same-length edits are supported")
|
||||
n = len(new) - 4
|
||||
delta = 0
|
||||
for j in range(n):
|
||||
d = old[j] ^ new[j]
|
||||
if d:
|
||||
delta ^= _zero_words(n - 1 - j, _feed_byte_as_word(0, d))
|
||||
crc = struct.unpack_from("<I", old, n)[0] ^ delta
|
||||
return bytes(new[:n]) + struct.pack("<I", crc)
|
||||
Reference in new issue
Block a user