"""Check part heights on a DIN-rail board against the printed housing. tools/.venv/bin/python tools/height_check.py projects//kicad/.kicad_pcb Finds the HW:DIN_Housing_TE footprint (its position is the housing centre), loads every top-side footprint's 3D model (STEP vertices, transformed like KiCad does) and compares each vertex with the height limit at its place, from tools/din_template.py dims(): - inside the front-cap box: h_tall; elsewhere h_low (bottom of the front-cap lip); - outside the step lines (|y| > y_step): the 45 deg shoulder slope, h_edge at the PCB edge and 1 mm more per mm inward. Parts that reach past the PCB edge are edge connectors: their notch runs up through the slope (DIN housing model), so they are listed but not judged against the slope. Bottom-side parts are not checked. Assembly STEP files (e.g. Phoenix's) cannot be placed without their transforms: for them the F.CrtYd outline at the model's top height is used and the result is flagged "approx". """ import math import os import re import sys import numpy as np sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import din_template # noqa: E402 import model_check # noqa: E402 import sexpr # noqa: E402 from kicad_paths import ROOT, FOOTPRINTS, SYMBOLS, MODELS3D # noqa: E402 ENV = { "HW_LIB": os.path.join(ROOT, "libraries"), "KICAD10_3DMODEL_DIR": MODELS3D, "KICAD9_3DMODEL_DIR": MODELS3D, } _cache = {} def vertices(path): """(points, exact) for a STEP file; assemblies fall back to all their points.""" if path not in _cache: try: _cache[path] = (model_check.step_vertices(path), True) except SystemExit: txt = open(path, encoding="latin-1").read() pts = re.findall(r"CARTESIAN_POINT\s*\(\s*'[^']*'\s*,\s*\(\s*([-\d.eE+]+)\s*,\s*([-\d.eE+]+)\s*,\s*([-\d.eE+]+)", txt) _cache[path] = (np.array(pts, dtype=float), False) return _cache[path] def resolve(path): path = re.sub(r"\$\{(\w+)\}", lambda m: ENV.get(m.group(1), m.group(0)), path) if not os.path.exists(path): for ext in (".step", ".stp"): alt = os.path.splitext(path)[0] + ext if os.path.exists(alt): return alt return None return path def xyz(node, key): n = sexpr.first(node, key) v = sexpr.first(n, "xyz") if n else None return np.array([float(a) for a in v[1:4]]) if v else np.zeros(3) if key != "scale" else np.ones(3) def courtyard(fp): """F.CrtYd corner points in footprint coordinates.""" pts = [] for kind in ("fp_line", "fp_rect", "fp_poly"): for g in sexpr.find(fp, kind): if str(sexpr.first(g, "layer")[1]) != "F.CrtYd": continue for key in ("start", "end"): n = sexpr.first(g, key) if n: pts.append([float(n[1]), float(n[2])]) if kind == "fp_rect": a, b = sexpr.first(g, "start"), sexpr.first(g, "end") pts += [[float(a[1]), float(b[2])], [float(b[1]), float(a[2])]] n = sexpr.first(g, "pts") pts += [[float(q[1]), float(q[2])] for q in sexpr.find(n, "xy")] if n else [] return np.array(pts) def model_points(fp): """Model vertices of a footprint in board coordinates (x, y down, z above the board).""" at = sexpr.first(fp, "at") fx, fy = float(at[1]), float(at[2]) fa = math.radians(float(at[3])) if len(at) > 3 else 0.0 c, s = math.cos(fa), math.sin(fa) out, exact = [], True for m in sexpr.find(fp, "model"): if sexpr.first(m, "hide"): continue path = resolve(str(m[1])) if not path or not path.lower().endswith((".step", ".stp")): continue P, ok = vertices(path) if not ok: # assembly: courtyard outline at the model's top height exact = False cy = courtyard(fp) if not len(cy): continue top = (P * xyz(m, "scale"))[:, 2].max() + xyz(m, "offset")[2] P = np.column_stack([cy[:, 0], -cy[:, 1], np.full(len(cy), top)]) rt = np.zeros(3) m = [None] else: rt = xyz(m, "rotate") R = model_check.rot(2, -rt[2]) @ model_check.rot(1, -rt[1]) @ model_check.rot(0, -rt[0]) if ok: P = (P * xyz(m, "scale")) @ R.T + xyz(m, "offset") P[:, 1] = -P[:, 1] x = P[:, 0] * c + P[:, 1] * s + fx y = -P[:, 0] * s + P[:, 1] * c + fy out.append(np.column_stack([x, y, P[:, 2]])) return (np.vstack(out) if out else None), exact def limit(d, u, v): """Height limit above the PCB at housing coordinates u, v (arrays).""" au, av = np.abs(u), np.abs(v) lim = np.where((au <= d["tall_x"]) & (av <= d["tall_y"]), d["h_tall"], d["h_low"]) slope = d["h_edge"] + d["pcb_h"] / 2 - av return np.where(av > d["y_step"], np.minimum(lim, slope), lim) def main(): board = sexpr.parse(open(sys.argv[1]).read()) fps = sexpr.find(board, "footprint") housing = [f for f in fps if re.match(r"HW:DIN_Housing_(\d+)TE$", str(f[1]))] if not housing: sys.exit("no HW:DIN_Housing_TE footprint on the board") k = int(re.match(r"HW:DIN_Housing_(\d+)TE$", str(housing[0][1])).group(1)) at = sexpr.first(housing[0], "at") cx, cy = float(at[1]), float(at[2]) d = din_template.dims(k) edge = d["pcb_h"] / 2 print("%d TE, centre (%.2f, %.2f): h_tall %.1f, h_low %.1f, step at |y| > %.1f: %.1f at the line to %.1f at the edge" % (k, cx, cy, d["h_tall"], d["h_low"], d["y_step"], d["h_edge"] + edge - d["y_step"], d["h_edge"])) bad, nomodel = 0, [] for fp in fps: if fp is housing[0] or str(sexpr.first(fp, "layer")[1]) != "F.Cu": continue ref = next((str(p[2]) for p in sexpr.find(fp, "property") if str(p[1]) == "Reference"), "?") P, exact = model_points(fp) if P is None: nomodel.append(ref) continue P = P[P[:, 2] > 0.05] if not len(P): continue u, v = P[:, 0] - cx, P[:, 1] - cy note = "" if exact else " (approx: assembly)" if np.abs(v).max() > edge + 0.05: print(" %-6s edge connector, %.1f mm tall, |y| %.1f..%.1f: needs a notch through the slope%s" % (ref, P[:, 2].max(), np.abs(v).min(), np.abs(v).max(), note)) continue over = P[:, 2] - limit(d, u, v) if over.max() > 0: bad += 1 i = over.argmax() print(" %-6s TOO TALL by %.1f mm: %.1f mm at (%.1f, %.1f) from the centre%s" % (ref, over[i], P[i, 2], u[i], -v[i], note)) if nomodel: print(" not checked (no STEP model): %s" % " ".join(sorted(nomodel))) print("%d part(s) too tall" % bad) sys.exit(1 if bad else 0) if __name__ == "__main__": main()