check_descriptors.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. #!/usr/bin/env python3
  2. """Regression check: re-emit each shipped panel from its GxEPD2 driver and diff
  3. the result against the committed components/gxepd2/panel_*.h.
  4. Compares only the structure the emitter authoritatively produces - the INIT /
  5. WINDOW / REFRESH command sequences, plane count, plane-write command(s),
  6. window_per_plane, and plane_invert - not the hand/diag-filled fields
  7. (bits_per_pixel/palette/blank_code/plane_width/line_order), which carry
  8. comments and names the emitter doesn't reproduce.
  9. Catches two things: an emitter regression (reproduction breaks), and GxEPD2
  10. upstream drift (a vendor bump changes a driver -> its panel now differs ->
  11. review it). Exit non-zero on any unexpected mismatch.
  12. tools/check_descriptors.py # check all
  13. tools/check_descriptors.py -v # show the diff on a mismatch
  14. Panels the emitter does not yet fully model (dual-region, see KNOWN_DIFF) are
  15. expected to differ and don't fail; if one of them starts MATCHING, that's an
  16. emitter improvement - remove it from KNOWN_DIFF. Panels with no GxEPD2 driver
  17. source (e.g. the synthetic MASTER_ONLY variant) are skipped.
  18. """
  19. import argparse
  20. import ast
  21. import pathlib
  22. import re
  23. import sys
  24. ROOT = pathlib.Path(__file__).resolve().parent.parent
  25. sys.path.insert(0, str(ROOT / "tools"))
  26. import capture as cap # noqa: E402 (resolution + emit, reused)
  27. PANEL_DIR = ROOT / "components" / "gxepd2"
  28. # Panels the emitter's segmentation doesn't reproduce yet. The dual-region
  29. # GDEY0579F51 used to live here; the emitter now models the region-select layer
  30. # (per-region init/window/refresh, plane_width, paired-edges line doubling), so
  31. # it reproduces and has been promoted out. A future panel the emitter can't yet
  32. # segment goes here with a one-line why.
  33. KNOWN_DIFF: set = set()
  34. def registry():
  35. """(model, part) for every entry in display.py's PANELS."""
  36. tree = ast.parse((PANEL_DIR / "display.py").read_text())
  37. for node in ast.walk(tree):
  38. if isinstance(node, ast.Assign) and any(getattr(t, "id", None) == "PANELS" for t in node.targets):
  39. for key, val in zip(node.value.keys, node.value.values):
  40. yield key.value
  41. return
  42. def parse_descriptor(text: str) -> dict:
  43. """Normalize a panel_*.h into the fields the emitter owns. Comments and
  44. array names are stripped, so only the command bytes / flags are compared."""
  45. text = re.sub(r"//.*", "", text)
  46. text = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
  47. arrs = {name: [int(x, 16) for x in re.findall(r"0x[0-9A-Fa-f]+", body)]
  48. for name, body in re.findall(r"uint8_t\s+(\w+)\[\]\s*=\s*\{([^}]*)\}", text)}
  49. seqs = {}
  50. for seqname, body in re.findall(r"EpdCommand\s+(\w+)\[\]\s*=\s*\{(.*?)\};", text, flags=re.S):
  51. cmds = []
  52. for line in re.findall(r"\{([^}]*)\}", body):
  53. parts = [p.strip() for p in line.split(",")]
  54. op = int(parts[0], 16)
  55. data = tuple(arrs.get(parts[1], [])) if parts[1] != "nullptr" else ()
  56. cmds.append((op, data, "true" in line))
  57. role = ("INIT" if "INIT" in seqname else "WINDOW" if "WINDOW" in seqname
  58. else "REFRESH" if "REFRESH" in seqname else seqname)
  59. seqs.setdefault(role, cmds) # first WINDOW_SEQ wins (window_sequence[0])
  60. def field(name, default="?"):
  61. m = re.search(rf"\.{name}\s*=\s*([^,\n]+)", text)
  62. return m.group(1).strip() if m else default
  63. return {
  64. "INIT": seqs.get("INIT"),
  65. "WINDOW": seqs.get("WINDOW", []),
  66. "REFRESH": seqs.get("REFRESH"),
  67. "plane_count": field("plane_count"),
  68. "plane_write_cmd": field("plane_write_cmd"),
  69. "window_per_plane": field("window_per_plane", "false"),
  70. "plane_invert": field("plane_invert"),
  71. }
  72. def check(model: str, catalog: dict, verbose: bool) -> str:
  73. """Returns 'MATCH', 'DIFF', 'XFAIL', 'XPASS', 'SKIP', or 'ERROR'."""
  74. panel_h = PANEL_DIR / cap.filename_of(model)
  75. if not panel_h.exists():
  76. return "SKIP"
  77. src_rel, _, _ = cap.resolve_source(model, catalog)
  78. if src_rel is None:
  79. return "SKIP" # no GxEPD2 driver to re-emit from (e.g. synthetic variant)
  80. try:
  81. generated = cap.capture(model, catalog, debug=False, cxx="g++", keep=False)
  82. except SystemExit as e:
  83. print(f" {e}", file=sys.stderr)
  84. return "ERROR"
  85. g, h = parse_descriptor(generated), parse_descriptor(panel_h.read_text())
  86. same = g == h
  87. expected_diff = model in KNOWN_DIFF
  88. if same:
  89. return "XPASS" if expected_diff else "MATCH"
  90. if expected_diff:
  91. return "XFAIL"
  92. if verbose:
  93. for k in g:
  94. if g[k] != h[k]:
  95. print(f" {k}:\n emitted : {g[k]}\n committed: {h[k]}", file=sys.stderr)
  96. return "DIFF"
  97. def main() -> None:
  98. ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  99. ap.add_argument("-v", "--verbose", action="store_true", help="show the fields that differ on a mismatch")
  100. args = ap.parse_args()
  101. catalog = cap.load_catalog()
  102. results = {}
  103. for model in registry():
  104. # capture.py prints its own [capture] line to stderr; keep output tidy.
  105. res = check(model, catalog, args.verbose)
  106. results[model] = res
  107. print(f" {res:<6} {model}")
  108. bad = [m for m, r in results.items() if r in ("DIFF", "ERROR", "XPASS")]
  109. n_match = sum(1 for r in results.values() if r == "MATCH")
  110. print(f"\n{n_match} reproduced, {sum(1 for r in results.values() if r=='XFAIL')} known-diff, "
  111. f"{sum(1 for r in results.values() if r=='SKIP')} skipped.")
  112. if bad:
  113. print("\nFAILURES:")
  114. for m in bad:
  115. why = {"DIFF": "command structure changed (emitter regression or GxEPD2 drift) - review",
  116. "ERROR": "capture failed to build/run",
  117. "XPASS": "now reproduces - remove from KNOWN_DIFF"}[results[m]]
  118. print(f" {results[m]:<6} {m}: {why}")
  119. sys.exit(1)
  120. print("OK")
  121. if __name__ == "__main__":
  122. main()