check_descriptors.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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/row_interleave), 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. # Dual-region panels the emitter's single/shared-region segmentation doesn't
  29. # model yet (its init/refresh region-select layer). Expected to differ.
  30. KNOWN_DIFF = {"GxEPD2_579c_GDEY0579F51"}
  31. def registry():
  32. """(model, part) for every entry in display.py's PANELS."""
  33. tree = ast.parse((PANEL_DIR / "display.py").read_text())
  34. for node in ast.walk(tree):
  35. if isinstance(node, ast.Assign) and any(getattr(t, "id", None) == "PANELS" for t in node.targets):
  36. for key, val in zip(node.value.keys, node.value.values):
  37. yield key.value
  38. return
  39. def parse_descriptor(text: str) -> dict:
  40. """Normalize a panel_*.h into the fields the emitter owns. Comments and
  41. array names are stripped, so only the command bytes / flags are compared."""
  42. text = re.sub(r"//.*", "", text)
  43. text = re.sub(r"/\*.*?\*/", "", text, flags=re.S)
  44. arrs = {name: [int(x, 16) for x in re.findall(r"0x[0-9A-Fa-f]+", body)]
  45. for name, body in re.findall(r"uint8_t\s+(\w+)\[\]\s*=\s*\{([^}]*)\}", text)}
  46. seqs = {}
  47. for seqname, body in re.findall(r"EpdCommand\s+(\w+)\[\]\s*=\s*\{(.*?)\};", text, flags=re.S):
  48. cmds = []
  49. for line in re.findall(r"\{([^}]*)\}", body):
  50. parts = [p.strip() for p in line.split(",")]
  51. op = int(parts[0], 16)
  52. data = tuple(arrs.get(parts[1], [])) if parts[1] != "nullptr" else ()
  53. cmds.append((op, data, "true" in line))
  54. role = ("INIT" if "INIT" in seqname else "WINDOW" if "WINDOW" in seqname
  55. else "REFRESH" if "REFRESH" in seqname else seqname)
  56. seqs.setdefault(role, cmds) # first WINDOW_SEQ wins (window_sequence[0])
  57. def field(name, default="?"):
  58. m = re.search(rf"\.{name}\s*=\s*([^,\n]+)", text)
  59. return m.group(1).strip() if m else default
  60. return {
  61. "INIT": seqs.get("INIT"),
  62. "WINDOW": seqs.get("WINDOW", []),
  63. "REFRESH": seqs.get("REFRESH"),
  64. "plane_count": field("plane_count"),
  65. "plane_write_cmd": field("plane_write_cmd"),
  66. "window_per_plane": field("window_per_plane", "false"),
  67. "plane_invert": field("plane_invert"),
  68. }
  69. def check(model: str, catalog: dict, verbose: bool) -> str:
  70. """Returns 'MATCH', 'DIFF', 'XFAIL', 'XPASS', 'SKIP', or 'ERROR'."""
  71. panel_h = PANEL_DIR / cap.filename_of(model)
  72. if not panel_h.exists():
  73. return "SKIP"
  74. src_rel, _, _ = cap.resolve_source(model, catalog)
  75. if src_rel is None:
  76. return "SKIP" # no GxEPD2 driver to re-emit from (e.g. synthetic variant)
  77. try:
  78. generated = cap.capture(model, catalog, debug=False, cxx="g++", keep=False)
  79. except SystemExit as e:
  80. print(f" {e}", file=sys.stderr)
  81. return "ERROR"
  82. g, h = parse_descriptor(generated), parse_descriptor(panel_h.read_text())
  83. same = g == h
  84. expected_diff = model in KNOWN_DIFF
  85. if same:
  86. return "XPASS" if expected_diff else "MATCH"
  87. if expected_diff:
  88. return "XFAIL"
  89. if verbose:
  90. for k in g:
  91. if g[k] != h[k]:
  92. print(f" {k}:\n emitted : {g[k]}\n committed: {h[k]}", file=sys.stderr)
  93. return "DIFF"
  94. def main() -> None:
  95. ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  96. ap.add_argument("-v", "--verbose", action="store_true", help="show the fields that differ on a mismatch")
  97. args = ap.parse_args()
  98. catalog = cap.load_catalog()
  99. results = {}
  100. for model in registry():
  101. # capture.py prints its own [capture] line to stderr; keep output tidy.
  102. res = check(model, catalog, args.verbose)
  103. results[model] = res
  104. print(f" {res:<6} {model}")
  105. bad = [m for m, r in results.items() if r in ("DIFF", "ERROR", "XPASS")]
  106. n_match = sum(1 for r in results.values() if r == "MATCH")
  107. print(f"\n{n_match} reproduced, {sum(1 for r in results.values() if r=='XFAIL')} known-diff, "
  108. f"{sum(1 for r in results.values() if r=='SKIP')} skipped.")
  109. if bad:
  110. print("\nFAILURES:")
  111. for m in bad:
  112. why = {"DIFF": "command structure changed (emitter regression or GxEPD2 drift) - review",
  113. "ERROR": "capture failed to build/run",
  114. "XPASS": "now reproduces - remove from KNOWN_DIFF"}[results[m]]
  115. print(f" {results[m]:<6} {m}: {why}")
  116. sys.exit(1)
  117. print("OK")
  118. if __name__ == "__main__":
  119. main()