"""Build a .tft from a .HMI project -- research stage. See docs/FORMAT.md section 7. What is reproduced byte for byte (Nextion Editor 1.68.2, model NX4832T035): header, resource area (the firmware files are read from the user's own Editor installation; pictures, fonts), page section for the component types in ``TYPES`` and the script subset in :mod:`nxhmi.tft_code`, layout table and all checksums. Anything else raises :class:`Unsupported` -- never a guess. """ from __future__ import annotations import os import re import struct from . import tft, tft_code from .container import HMIFile from .page import Page from .checksum import word_per_byte_crc from .tft_code import Unsupported FIRMWARE_FILES = ("input.bin", "asp0.dll", "cd0.dll", "qr0.bin", "syscom.bin", "h0-0.dll", "h1-0.dll") DEFAULT_EDITOR_DIR = r"C:\Program Files (x86)\Nextion Editor" SUPPORTED_MODEL = 0xB23BC018 # NX4832T035_011, the only model measured BLOCK = 0x10000 # attribute map positions in the object record (u16 table at +0x38) MAP = {"vscope": 1, "sta": 2, "bco": 4, "val": 20, "tim": 33, "en": 34, "x": 42, "y": 43, "endx": 44, "endy": 45, "w": 46, "h": 47, "id": 49, "type": 62} # attribute record templates: name -> (slot, kind, size, max, min) _COMMON = {"type": (0, 0x01, 1, 255, 0), "id": (1, 0x01, 1, 255, 0), "vscope": (3, 0x01, 1, 1, 0)} _RECT = {"x": (9, 0x0B, 2, 6000, -6000), "y": (10, 0x0C, 2, 6000, -6000), "w": (11, 0x0D, 2, 2000, -2000), "h": (12, 0x0E, 2, 2000, -2000), "endx": (13, 0x08, 2, 32767, -32768), "endy": (14, 0x08, 2, 32767, -32768)} # type id -> description. ``ram`` attributes live in the page's RAM image (in this order); # ``owner``: whether records name the component to refresh when the attribute changes. TYPES = { 121: dict(name="page", slots=33, flag=0x37, group=8, const={**_COMMON, **_RECT}, ram={"sta": (23, 0x21, 1, 2, 0), "bco": (24, 0x32, 2, 65535, 0)}, owner=True), 109: dict(name="hotspot", slots=27, flag=0x37, group=16, const={**_COMMON, **_RECT}, ram={}, owner=True), 52: dict(name="variable", slots=11, flag=0x07, group=16, const={**_COMMON, "sta": (7, 0x01, 1, 1, 0)}, ram={"val": (8, 0x39, 4, 2147483647, -2147483648)}, owner=False), 51: dict(name="timer", slots=11, flag=0x27, group=16, const=dict(_COMMON), ram={"tim": (7, 0x32, 2, 65534, 50), "en": (8, 0x31, 1, 1, 0)}, owner=True, action={"tim": 1, "en": 2}), } def _chunk(b: bytes) -> bytes: return struct.pack(" int: return int.from_bytes(attr.value, "little") def _s(attr, signed) -> int: v, bits = _u(attr), 8 * len(attr.value) return v - (1 << bits) if signed and v >> (bits - 1) else v def resource_area(hmi: HMIFile, editor_dir: str) -> tuple[bytes, dict]: """Directory + firmware files + pictures + fonts, zero-padded to a 64 KB multiple.""" def numbered(ext): names = [n for n in hmi.names() if re.fullmatch(r"\d+\." + ext, n)] return [hmi.read(n) for n in sorted(names, key=lambda s: int(s.split(".")[0]))] def packed(blobs, head, off_pos, idx_pos=None): heads, datas, o = [], [], head * len(blobs) for i, b in enumerate(blobs): h = bytearray(b[:head]) struct.pack_into(" (code blob, global variable descriptors, attribute records, page table, object records, program offset).""" names = sorted((tft.name_hash(p.components[0].get("objname")), i) for i, p in enumerate(pages)) n = len(pages) decl, program_lines = tft_code.declarations(tft_code.statements(program.splitlines())) if any(v < 0 for v in decl.values()): raise Unsupported("global variables with a negative initial value") g = 4 * len(decl) blob = bytearray(struct.pack("<8I", 0x24 + g + 6 * n, 3, 0x1C, 4, 0x20, 4 + g, 0x24 + g, 6 * n)) blob += bytes(4) + b"".join(struct.pack(" (first record, type) for page in pages: pname = page.components[0].get("objname") for c in page.components: tid = _u(c.attr("type")) if tid not in TYPES: raise Unsupported("component type %d (%s)" % (tid, c.get("objname"))) where[(pname, c.get("objname"))] = (base_rec, TYPES[tid]) base_rec += TYPES[tid]["slots"] current = [None] def attr(path): if len(path) == 3: key, name = (path[0], path[1]), path[2] elif len(path) == 2: key, name = (current[0], path[0]), path[1] else: return None if key not in where: return None first, t = where[key] slot = {**t["const"], **t["ram"]}.get(name) return None if slot is None else first + slot[0] ctx = tft_code.Context(offsets, {k[1] for k in where}, attr) def section(lines, label=None): if label: blob.extend(_chunk(label)) for c in tft_code.compile_lines(lines, ctx): blob.extend(_chunk(c)) blob.extend(_chunk(b"")) section(program_lines + ["page 0"]) records, objects, table, rec_base = bytearray(), bytearray(), [], 0 for pi, page in enumerate(pages): ram = bytearray(b"\xff" * 8) prec, first_obj, comp_names, init = bytearray(), len(objects) // tft.OBJ_SIZE, [], [] page_bco = 0 pre, post = [], [] current[0] = page.components[0].get("objname") for ci, c in enumerate(page.components): a = {x.name: x for x in c.attrs()} tid = _u(a["type"]) if tid not in TYPES or (ci == 0) != (tid == 121): raise Unsupported("component type %d (%s) on page %d" % (tid, c.get("objname"), pi)) t = TYPES[tid] if tid == 121 and _u(a["sta"]) != 1: raise Unsupported("page background other than a solid colour") if tid == 52 and _u(a["sta"]) != 0: raise Unsupported("string variables") if _u(a["vscope"]) != 0: raise Unsupported("global components") cid = _u(a["id"]) owner = struct.pack("", the event lines; registered by two init lines blob += _chunk(b"timer") code_at[2] = len(blob) blob += _chunk(b"S \x03" + struct.pack(" bytes: main = hmi.read("main.HMI") model, = struct.unpack_from("