check_descriptors.py 6.7 KB

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