"""Generate DIN-rail board templates: housing footprint + KiCad project per TE. Run with KiCad's bundled Python (needs pcbnew): $KICAD_PYTHON tools/din_template.py 4 5 6 (see tools/kicad_env.sh) Writes, for each TE count k: libraries/footprints/HW.pretty/DIN_Housing_TE.kicad_mod libraries/templates/DIN_TE/ (project template for KiCad's "New Project from Template") The 3D model libraries/3dmodels/HW.3dshapes/DIN_Housing_TE.step must be exported from the DIN housing model at TE = k (bodies Shell, Plate, FrontCap, Spacer_*); the model is not part of the toolchain, the footprint and templates work without it. Dimensions mirror the housing model's parameters; keep the two in sync. """ import json import math import os import sys import uuid import netclasses from kicad_paths import ROOT, FOOTPRINTS, SYMBOLS, MODELS3D # noqa: E402 PRETTY = os.path.join(ROOT, "libraries/footprints/HW.pretty") TEMPLATES = os.path.join(ROOT, "libraries/templates") PRO_SOURCE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "din_base.kicad_pro") # design rules; net classes from netclasses.py # Housing parameters (SolidCraft names) PITCH, H, WALL, FIT, PCB_GAP = 18.0, 90.0, 2.0, 0.2, 0.5 D_SH, D_TOT, LIP_T, LIP_H = 45.0, 58.0, 1.2, 3.0 FRONT_W = 44.5 PLATE_T, SPACER_H, PCB_T = 4.6, 4.0, 1.6 POST_D, RIB_W, POST_EX, POST_EY = 7.0, 3.0, 4.5, 14.0 SPACER_D, HOLE_D = 6.0, 3.2 TERM_H, STEP_W = 8.5, 10.0 # shoulder step: tallest edge connector, end face to riser CY = 0.25 # courtyard margin Z_PCB = PLATE_T + SPACER_H + PCB_T # top of PCB above the back plane SH_E = Z_PCB + TERM_H + 0.5 + WALL * (math.sqrt(2) - 1) # end-wall top; 45 deg slope up to the riser CENTRE = (150.0, 100.0) # board centre on the A4 sheet def dims(k): w = k * PITCH - 0.5 pcb_w, pcb_h = w - 2 * WALL - 2 * PCB_GAP, H - 2 * WALL - 2 * PCB_GAP return { "W": w, "pcb_w": pcb_w, "pcb_h": pcb_h, "x_post": pcb_w / 2 - POST_EX, "y_post": pcb_h / 2 - POST_EY, # inside of the front-cap lip: full height only within this box "tall_x": w / 2 - WALL - FIT - LIP_T, "tall_y": FRONT_W / 2 - WALL - FIT - LIP_T, "h_tall": D_TOT - WALL - Z_PCB, # to the inside of the front cap "h_low": D_SH - LIP_H - Z_PCB, # to the bottom of the lip (the shoulder is higher) "h_bot": SPACER_H, # under the 45 deg shoulder step: limit at the PCB edge, rising 1:1 inward up to the riser "y_step": H / 2 - STEP_W - WALL, # inner face of the riser "h_edge": SH_E - WALL * math.sqrt(2) + (H / 2 - pcb_h / 2) - Z_PCB, } def f(v): return ("%.4f" % v).rstrip("0").rstrip(".") def line(layer, a, b, width=0.05): return ('\t(fp_line (start %s %s) (end %s %s) (stroke (width %s) (type solid)) (layer "%s"))\n' % (f(a[0]), f(a[1]), f(b[0]), f(b[1]), f(width), layer)) def arc(layer, a, m, b, width=0.05): return ('\t(fp_arc (start %s %s) (mid %s %s) (end %s %s) (stroke (width %s) (type solid)) (layer "%s"))\n' % (f(a[0]), f(a[1]), f(m[0]), f(m[1]), f(b[0]), f(b[1]), f(width), layer)) def circle(layer, c, r, width=0.05): return ('\t(fp_circle (center %s %s) (end %s %s) (stroke (width %s) (type solid)) (fill no) (layer "%s"))\n' % (f(c[0]), f(c[1]), f(c[0] + r), f(c[1]), f(width), layer)) def rect(layer, a, b, width=0.1, dash=False): return ('\t(fp_rect (start %s %s) (end %s %s) (stroke (width %s) (type %s)) (fill no) (layer "%s"))\n' % (f(a[0]), f(a[1]), f(b[0]), f(b[1]), f(width), "dash" if dash else "solid", layer)) def text(layer, s, at, size=1.0, hidden=False): return ('\t(fp_text user "%s" (at %s %s 0) (layer "%s")%s (effects (font (size %s %s) (thickness %s)) (justify left)))\n' % (s, f(at[0]), f(at[1]), layer, " (hide yes)" if hidden else "", f(size), f(size), f(size * 0.15))) def footprint(k): d = dims(k) hx, hy = d["pcb_w"] / 2, d["pcb_h"] / 2 name = "DIN_Housing_%dTE" % k out = ['(footprint "%s"\n\t(version 20260206)\n\t(generator "din_template.py")\n\t(layer "F.Cu")\n' % name, '\t(descr "Mounting and keep-outs for the printed DIN-rail housing, %d TE (outer %s mm wide), ' 'PCB %s x %s mm. Origin = board centre. Generated by tools/din_template.py; see knowledge/topics/din-rail-format.md")\n' % (k, f(d["W"]), f(d["pcb_w"]), f(d["pcb_h"])), '\t(tags "DIN rail housing enclosure")\n', '\t(property "Reference" "ENC1" (at 0 %s 0) (layer "F.Fab") (effects (font (size 1 1) (thickness 0.15))))\n' % f(-hy + 2), '\t(property "Value" "%s" (at 0 %s 0) (layer "F.Fab") (effects (font (size 1 1) (thickness 0.15))))\n' % (name, f(hy - 2)), '\t(attr board_only exclude_from_pos_files exclude_from_bom)\n'] a = math.sqrt((POST_D / 2 + CY) ** 2 - (RIB_W / 2 + CY) ** 2) rp, rh = POST_D / 2 + CY, RIB_W / 2 + CY for sx in (1, -1): for sy in (1, -1): x0, y0 = sx * d["x_post"], sy * d["y_post"] # top: post (Ø7) plus the rib that runs from it to the side wall p1, p2 = (x0 + sx * a, y0 - rh), (x0 + sx * a, y0 + rh) out += [line("F.CrtYd", p2, (sx * hx, y0 + rh)), line("F.CrtYd", (sx * hx, y0 + rh), (sx * hx, y0 - rh)), line("F.CrtYd", (sx * hx, y0 - rh), p1), arc("F.CrtYd", p1, (x0 - sx * rp, y0), p2)] # bottom: spacer out.append(circle("B.CrtYd", (x0, y0), SPACER_D / 2 + CY)) out.append(circle("Cmts.User", (x0, y0), POST_D / 2, 0.1)) out.append('\t(pad "" np_thru_hole circle (at %s %s) (size %s %s) (drill %s) (layers "*.Cu" "*.Mask"))\n' % (f(x0), f(y0), f(HOLE_D), f(HOLE_D), f(HOLE_D))) # height zones and notes tx, ty = min(d["tall_x"], hx), d["tall_y"] out.append(rect("Dwgs.User", (-tx, -ty), (tx, ty), 0.15, dash=True)) for sy in (1, -1): # shoulder step: the 45 deg slope starts above these lines out.append('\t(fp_line (start %s %s) (end %s %s) (stroke (width 0.15) (type dash)) (layer "Dwgs.User"))\n' % (f(-hx), f(sy * d["y_step"]), f(hx), f(sy * d["y_step"]))) h_step = d["h_edge"] + hy - d["y_step"] notes = ["%d TE: top parts max %s mm above PCB, max %s mm inside dashed box" % (k, f(math.floor(d["h_low"])), f(math.floor(d["h_tall"]))), "outside the dashed step lines: 45 deg slope, max %s mm at the line down to %s mm at the edge" % (f(math.floor(h_step * 10) / 10), f(math.floor(d["h_edge"] * 10) / 10)), "bottom parts and THT leads max %s mm (spacers %s mm)" % (f(d["h_bot"] - 1), f(d["h_bot"])), "no connectors past the edge without a notch in the shell"] for i, s in enumerate(notes): out.append(text("Dwgs.User", s, (-hx + 1, -ty + 2.5 + 1.6 * i), 1.0)) out.append('\t(model "${HW_LIB}/3dmodels/HW.3dshapes/%s.step"\n\t\t(opacity 0.35)\n' '\t\t(offset (xyz 0 0 %s))\n\t\t(scale (xyz 1 1 1))\n\t\t(rotate (xyz 0 0 0))\n\t)\n' % (name, f(-Z_PCB))) out.append('\t(embedded_fonts no)\n)\n') path = os.path.join(PRETTY, name + ".kicad_mod") with open(path, "w") as fh: fh.write("".join(out)) return name def project_json(proj): with open(PRO_SOURCE) as fh: d = json.load(fh) d["meta"]["filename"] = proj + ".kicad_pro" d["sheets"], d["boards"], d["text_variables"] = [["%s" % uuid.uuid4(), "Root"]], [], {} d["schematic"]["top_level_sheets"] = [{"filename": proj + ".kicad_sch", "name": proj, "uuid": d["sheets"][0][0]}] d["board"]["design_settings"]["drc_exclusions"] = [] d["net_settings"]["netclass_assignments"] = None netclasses.apply(d) # shared classes, patterns and width/via palettes d.get("pcbnew", {}).pop("last_paths", None) return d def schematic(proj, k, d, sheet_uuid): note = ("DIN-rail board, %d TE: housing %s x 90 mm, PCB %s x %s mm.\\n" "Mounting holes and keep-outs: footprint DIN_Housing_%dTE on the PCB (not in schematic).\\n" "Format and rules: knowledge/topics/din-rail-format.md" % (k, f(d["W"]), f(d["pcb_w"]), f(d["pcb_h"]), k)) return ('(kicad_sch\n\t(version 20250610)\n\t(generator "eeschema")\n\t(generator_version "10.0")\n' '\t(uuid "%s")\n\t(paper "A4")\n\t(title_block\n\t\t(title "${PROJECTNAME}")\n' '\t\t(comment 1 "DIN-rail board %d TE")\n\t)\n\t(lib_symbols)\n' '\t(text "%s"\n\t\t(exclude_from_sim no)\n\t\t(at 25.4 25.4 0)\n' '\t\t(effects (font (size 1.27 1.27)) (justify left top))\n\t\t(uuid "%s")\n\t)\n' '\t(sheet_instances\n\t\t(path "/" (page "1"))\n\t)\n\t(embedded_fonts no)\n)\n' % (sheet_uuid, k, note, uuid.uuid4())) def board(proj, k, d, fp_name, path): import pcbnew # only here, so tools/height_check.py can import dims() without KiCad's Python b = pcbnew.NewBoard(path) M, V = pcbnew.FromMM, pcbnew.VECTOR2I cx, cy = CENTRE hx, hy = d["pcb_w"] / 2, d["pcb_h"] / 2 edge = pcbnew.PCB_SHAPE(b, pcbnew.SHAPE_T_RECTANGLE) edge.SetStart(V(M(cx - hx), M(cy - hy))) edge.SetEnd(V(M(cx + hx), M(cy + hy))) edge.SetLayer(pcbnew.Edge_Cuts) edge.SetWidth(M(0.05)) b.Add(edge) fp = pcbnew.FootprintLoad(PRETTY, fp_name) fp.SetFPID(pcbnew.LIB_ID("HW", fp_name)) fp.SetPosition(V(M(cx), M(cy))) fp.SetLocked(True) b.Add(fp) ds = b.GetDesignSettings() ds.SetBoardThickness(M(PCB_T)) ds.SetAuxOrigin(V(M(cx), M(cy))) ds.SetGridOrigin(V(M(cx), M(cy))) tb = b.GetTitleBlock() tb.SetTitle("${PROJECTNAME}") tb.SetComment(0, "DIN-rail board %d TE, PCB %s x %s mm, origin = board centre" % (k, f(d["pcb_w"]), f(d["pcb_h"]))) pcbnew.SaveBoard(path, b) def info_html(k, d): return ("\nDIN-rail board %d TE\n\n

DIN-rail board %d TE

\n" "

Base PCB for the printed DIN-rail housing : outer width %s mm, " "PCB %s × %s mm, 1.6 mm thick, four M3 holes at the corners. " "Footprint HW:DIN_Housing_%dTE carries the holes, post and spacer courtyards, height zones " "and the housing 3D model (hide it with the 3D viewer's 'Unspecified' toggle).

\n" "

Top parts: max %d mm, or %d mm inside the dashed box. Outside the dashed step lines " "(outer %s mm of the PCB) the shoulder slopes at 45°: max %s mm at the PCB edge, 1 mm more per mm inward. " "Bottom parts: max %s mm.

\n" "

Rules and decisions: knowledge/topics/din-rail-format.md

\n\n\n" % (k, k, f(d["W"]), f(d["pcb_w"]), f(d["pcb_h"]), k, math.floor(d["h_low"]), math.floor(d["h_tall"]), f(d["pcb_h"] / 2 - d["y_step"]), f(math.floor(d["h_edge"] * 10) / 10), f(d["h_bot"] - 1))) def main(ks): for k in ks: d = dims(k) fp_name = footprint(k) proj = "DIN_%dTE" % k tdir = os.path.join(TEMPLATES, proj) os.makedirs(os.path.join(tdir, "meta"), exist_ok=True) pro = project_json(proj) board(proj, k, d, fp_name, os.path.join(tdir, proj + ".kicad_pcb")) with open(os.path.join(tdir, proj + ".kicad_pro"), "w") as fh: # overwrite NewBoard's default json.dump(pro, fh, indent=2) fh.write("\n") with open(os.path.join(tdir, proj + ".kicad_sch"), "w") as fh: fh.write(schematic(proj, k, d, pro["sheets"][0][0])) with open(os.path.join(tdir, "meta", "info.html"), "w") as fh: fh.write(info_html(k, d)) print("%s: PCB %s x %s, holes at +-%s/+-%s" % (proj, f(d["pcb_w"]), f(d["pcb_h"]), f(d["x_post"]), f(d["y_post"]))) if __name__ == "__main__": main([int(a) for a in sys.argv[1:]] or [4, 5, 6])