aboutsummaryrefslogtreecommitdiff
path: root/tools/housing_inputs.py
blob: 1080c7919cd714f893818ab4b7f90ac3bd1a71e3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
"""Numbers for a project's DIN-rail housing: notches, pockets, spacer-frame tongues and pin cutouts.

    tools/.venv/bin/python tools/housing_inputs.py projects/<name>/kicad/<name>.kicad_pcb

Prints, in housing coordinates (X along the rail, Y up = board -y, origin at the
HW:DIN_Housing_<k>TE footprint), what the per-project changes of the DIN housing model need:
- per PCB tab on Edge.Cuts: its X range and the edge connectors on it, each with the back of its
  body (|y|, from the 3D model; assembly models use the courtyard, flagged "approx"), its height
  above the PCB and the notch kind the README rules give (screw terminal, side-entry window,
  notch from the riser);
- the spacer frame's pin cutouts: per footprint with through-hole pads under the frame, the pad
  rectangle grown by PIN_CLR, and cutouts closer than MERGE_GAP that should be merged;
- bottom-side footprints, which the frame does not account for.
"""
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 height_check  # noqa: E402
import sexpr  # noqa: E402

# Same values as the DIN housing model's parameters
TAB = 2.0  # PCB tab under an edge connector
STEP_W = 10.0  # shoulder step: riser at |y| = H/2 - STEP_W
TERM_H = 8.5  # tallest terminal under the step; the slope underside clears it by 0.5 at the wall
NOTCH_BACK_CLR = 0.5  # screw terminal: notch starts this far behind the body
WINDOW_CLR = 1.0  # side-entry window: this far above the body
FRAME_Y0 = 27.5  # spacer frame: inner edge of the end bars
FRAME_RAIL = 4.0  # spacer frame: side rail width
PIN_CLR = 1.5  # spacer frame: cutout margin around through-hole pads
MERGE_GAP = 1.0  # cutouts closer than this leave a sliver: merge them


def ref_of(fp):
    return next((str(p[2]) for p in sexpr.find(fp, "property") if str(p[1]) == "Reference"), "?")


def tabs(board, cx, cy, edge):
    """X ranges (housing) of the Edge.Cuts segments that run along |y| = edge + TAB, per side."""
    out = {1: [], -1: []}
    for g in sexpr.find(board, "gr_line"):
        if str(sexpr.first(g, "layer")[1]) != "Edge.Cuts":
            continue
        a, b = sexpr.first(g, "start"), sexpr.first(g, "end")
        y1, y2 = cy - float(a[2]), cy - float(b[2])
        if abs(y1 - y2) < 1e-3 and abs(abs(y1) - (edge + TAB)) < 0.05:
            xs = sorted([float(a[1]) - cx, float(b[1]) - cx])
            out[1 if y1 > 0 else -1].append(tuple(xs))
    return {s: sorted(v) for s, v in out.items()}


def pads(fp):
    """Through-hole pad centres in board coordinates."""
    at = sexpr.first(fp, "at")
    fx, fy = float(at[1]), float(at[2])
    a = math.radians(float(at[3])) if len(at) > 3 else 0.0
    out = []
    for p in sexpr.find(fp, "pad"):
        if str(p[2]) not in ("thru_hole", "np_thru_hole"):
            continue
        pa = sexpr.first(p, "at")
        lx, ly = float(pa[1]), float(pa[2])
        out.append((fx + lx * math.cos(a) + ly * math.sin(a), fy - lx * math.sin(a) + ly * math.cos(a)))
    return out


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_<k>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
    riser = din_template.H / 2 - STEP_W
    window_max = TERM_H + 0.5  # slope underside at the inner end-wall face, above the PCB
    print("%d TE, centre (%.2f, %.2f); housing X = board x - %.2f, Y = %.2f - board y; riser at |y| %.1f"
          % (k, cx, cy, cx, cy, riser))

    conns = []
    for fp in fps:
        if fp is housing[0] or str(sexpr.first(fp, "layer")[1]) != "F.Cu":
            continue
        P, exact = height_check.model_points(fp)
        if P is None:
            continue
        P = P[P[:, 2] > 0.05]
        if not len(P) or np.abs(P[:, 1] - cy).max() <= edge + 0.05:
            continue
        u, v = P[:, 0] - cx, cy - P[:, 1]
        conns.append((ref_of(fp), str(fp[1]), 1 if v.mean() > 0 else -1, u.min(), u.max(),
                      np.abs(v).min(), P[:, 2].max(), exact))

    print("\nPCB tabs and edge connectors (notch X = tab +- notch_clr, tongue X = tab +- (notch_clr - fit)):")
    for side, ranges in tabs(board, cx, cy, edge).items():
        for x1, x2 in ranges:
            print("  %s tab X %.2f .. %.2f (length %.2f)" % ("top   " if side > 0 else "bottom", x1, x2, x2 - x1))
            for ref, name, s, u1, u2, back, h, exact in conns:
                if s != side or u2 < x1 or u1 > x2:
                    continue
                if "TerminalBlock" in name:
                    kind = "screw terminal: notch from |y| %.2f (body back - %.1f), pocket back wall there" % (
                        back - NOTCH_BACK_CLR, NOTCH_BACK_CLR)
                elif h + WINDOW_CLR <= window_max:
                    kind = "side-entry: slope stays closed, end-wall window up to %.1f above the PCB" % (h + WINDOW_CLR)
                else:
                    kind = "notch from the riser (|y| %.1f)%s" % (
                        riser, ", back wall above the body" if back < riser else "")
                print("    %-6s body back |y| %.2f, %.1f mm tall%s; %s"
                      % (ref, back, h, "" if exact else " (approx: assembly)", kind))

    # spacer frame region: end bars |y| >= FRAME_Y0, side rails |x| >= inner edge of the rail
    rail_x = d["W"] / 2 - din_template.WALL - din_template.FIT - FRAME_RAIL
    rects = []
    for fp in fps:
        if fp is housing[0]:
            continue
        P = [(x - cx, cy - y) for x, y in pads(fp)]
        P = [(u, v) for u, v in P if abs(v) >= FRAME_Y0 - PIN_CLR or abs(u) >= rail_x - PIN_CLR]
        if P:
            us, vs = [p[0] for p in P], [p[1] for p in P]
            rects.append((ref_of(fp), min(us) - PIN_CLR, max(us) + PIN_CLR, min(vs) - PIN_CLR, max(vs) + PIN_CLR))
    print("\nSpacer-frame pin cutouts (pad rectangle +- %.1f, through the frame):" % PIN_CLR)
    for ref, a, b, c, e in sorted(rects, key=lambda r: (r[3] < 0, r[1])):
        print("  %-6s X %.2f .. %.2f, Y %.2f .. %.2f" % (ref, a, b, c, e))
    for i, r in enumerate(rects):
        for q in rects[i + 1:]:
            gx = max(q[1] - r[2], r[1] - q[2])
            gy = max(q[3] - r[4], r[3] - q[4])
            if max(gx, gy) < MERGE_GAP:
                print("  merge %s and %s: %.2f mm apart" % (r[0], q[0], max(gx, gy, 0)))

    bottom = [ref_of(f) for f in fps if str(sexpr.first(f, "layer")[1]) == "B.Cu"]
    print("\nBottom-side footprints (the frame ignores them; cut them free by hand): %s"
          % (" ".join(sorted(bottom)) if bottom else "none"))


if __name__ == "__main__":
    main()