diff options
Diffstat (limited to 'tools/schgen.py')
| -rw-r--r-- | tools/schgen.py | 302 |
1 files changed, 302 insertions, 0 deletions
diff --git a/tools/schgen.py b/tools/schgen.py new file mode 100644 index 0000000..92b3e84 --- /dev/null +++ b/tools/schgen.py @@ -0,0 +1,302 @@ +"""Write KiCad 10 schematics from Python: symbols, pin labels, power symbols, sheets. + +A module's generator (e.g. modules/<name>/tools/gen_sch.py) describes the circuit as +symbols placed on a grid, with every pin connected by a short wire stub and a net label, +power symbol, hierarchical label or no-connect flag. Wires between pins are possible +(Sheet.wire) but labels keep a generated sheet readable without a router. + + from schgen import Sheet + s = Sheet("my-project", "my_block.kicad_sch", sheet_name="My Block", root_uuid=..., sheet_uuid=...) + r = s.add("Device:R", "R1", 50.8, 50.8, value="10k", fp="Resistor_SMD:R_0603_1608Metric") + s.net(r, "1", "SIG") # stub + local label + s.power(r, "2", "GND") # stub + power symbol + s.write("path/my_block.kicad_sch") + +Symbols come from KiCad's shared libraries or the repo's HW library and are flattened into +lib_symbols (`extends` resolved). UUIDs are uuid5 of names, so the same script writes the +same file and a board keeps its links to the schematic. Pin positions follow KiCad's +transform: library Y up, sheet Y down, rotation counter-clockwise on screen. Mirroring is not +supported. Check the result with `kicad-cli sch erc` and `sch export netlist`. +Notes: knowledge/tooling/schgen.md +""" +import math +import os +import uuid + +from sexpr import Q, dump, find, first, parse + +from kicad_paths import ROOT, FOOTPRINTS, SYMBOLS, MODELS3D # noqa: E402 +LIBS = {"HW": os.path.join(ROOT, "libraries/symbols/HW.kicad_sym")} +G = 2.54 +STUB = 2.54 +NS = uuid.UUID("6f1b9a4e-2c55-4f0e-9b7d-3a1f0c8e5d21") +_libcache = {} + + +def uid(*parts): + return Q(str(uuid.uuid5(NS, "/".join(str(p) for p in parts)))) + + +def r4(v): + return round(v + 0.0, 4) + + +def _lib(nick): + if nick not in _libcache: + path = LIBS.get(nick, os.path.join(SYMBOLS, nick + ".kicad_sym")) + _libcache[nick] = {s[1]: s for s in find(parse(open(path).read()), "symbol")} + return _libcache[nick] + + +def load_symbol(lib_id): + """Flattened library symbol renamed to lib_id (the form lib_symbols wants).""" + nick, name = lib_id.split(":") + lib = _lib(nick) + sym = lib[name] + ext = first(sym, "extends") + if ext: + parent = load_symbol(nick + ":" + ext[1]) + props = {p[1]: p for p in find(sym, "property")} + out = [Q(lib_id)] + for item in parent[2:]: + if isinstance(item, list) and item[0] == "property" and item[1] in props: + out.append(props.pop(item[1])) + elif isinstance(item, list) and item[0] == "symbol": + out.append([item[0], Q(item[1].replace(ext[1] + "_", name + "_", 1))] + item[2:]) + else: + out.append(item) + # child-only properties go after the parent's + i = max(k for k, x in enumerate(out) if isinstance(x, list) and x[0] == "property") + out[i + 1:i + 1] = list(props.values()) + return ["symbol"] + out + out = ["symbol", Q(lib_id)] + [x for x in sym[2:]] + out = [x if not (isinstance(x, list) and x[0] == "symbol") else + [x[0], Q(x[1])] + x[2:] for x in out] + return out + + +def _subunits(sym): + """(unit, body style, sub-symbol) for each sub-symbol "Name_U_S".""" + for s in find(sym, "symbol"): + u, st = s[1].rsplit("_", 2)[-2:] + yield int(u), int(st), s + + +def pins_of(sym, unit): + """{number: (x, y, angle)} in library coordinates for one unit (body style 1).""" + pins = {} + for u, st, s in _subunits(sym): + if st not in (0, 1) or u not in (0, unit): + continue + for p in find(s, "pin"): + at = first(p, "at") + num = first(p, "number")[1] + pins[str(num)] = (float(at[1]), float(at[2]), float(at[3])) + return pins + + +def units_of(sym): + return sorted({u for u, st, s in _subunits(sym) if u > 0}) or [1] + + +def _xf(x, y, rot): + """Library point -> sheet offset for a symbol at rotation rot (degrees, CCW on screen).""" + a = math.radians(rot) + sx, sy = x, -y + return (sx * math.cos(a) + sy * math.sin(a), -sx * math.sin(a) + sy * math.cos(a)) + + +def _eff(justify=None, hide=False, size=1.27): + e = ["effects", ["font", ["size", size, size]]] + if justify: + e.append(["justify"] + justify.split()) + out = [] + if hide: + out.append(["hide", "yes"]) + return out + [e] + + +class Symbol: + def __init__(self, sheet, lib_id, ref, x, y, rot, unit): + self.sheet, self.lib_id, self.ref, self.x, self.y, self.rot, self.unit = sheet, lib_id, ref, x, y, rot, unit + self.lib = sheet.symbol(lib_id) + self.pins = pins_of(self.lib, unit) + + def pin(self, num): + """(x, y, outward unit vector) of a pin's connection point on the sheet.""" + px, py, pa = self.pins[str(num)] + dx, dy = _xf(px, py, self.rot) + # the library angle points from the connection point into the body + a = math.radians(pa + 180 + self.rot) + return (r4(self.x + dx), r4(self.y + dy), (round(math.cos(a)), -round(math.sin(a)))) + + +class Sheet: + """One schematic file. For the root sheet leave sheet_uuid None.""" + + def __init__(self, project, filename, root_uuid, sheet_uuid=None, sheet_name=None, paper="A4", page=None): + self.project, self.filename = project, filename + self.root_uuid, self.sheet_uuid, self.sheet_name = root_uuid, sheet_uuid, sheet_name + self.uuid = sheet_uuid or root_uuid + self.path = "/" + root_uuid + ("/" + sheet_uuid if sheet_uuid else "") + self.paper = paper + self.libsyms = {} + self.items = [] + self.npwr = 0 + self.nflg = 0 + self.seq = 0 + + def _uid(self, *parts): + self.seq += 1 + return uid(self.project, self.filename, self.seq, *parts) + + def symbol(self, lib_id): + if lib_id not in self.libsyms: + self.libsyms[lib_id] = load_symbol(lib_id) + return self.libsyms[lib_id] + + # ---------- symbols ---------- + def add(self, lib_id, ref, x, y, rot=0, unit=1, value=None, fp="", fields=None, datasheet=None, + in_bom=True, on_board=True, show_value=True, dnp=False): + s = Symbol(self, lib_id, ref, x, y, rot, unit) + lib = s.lib + props = {p[1]: p for p in find(lib, "property")} + val = value if value is not None else props["Value"][2] + e = ["symbol", ["lib_id", Q(lib_id)], ["at", r4(x), r4(y), rot], ["unit", unit], + ["exclude_from_sim", "no"], ["in_bom", "yes" if in_bom else "no"], + ["on_board", "yes" if on_board else "no"], ["dnp", "yes" if dnp else "no"], + ["uuid", uid(self.project, self.path, ref, unit)]] + + def prop(name, text, hide, at=None): + if at is None: + lp = props.get(name) + if lp is not None: + a = first(lp, "at") + dx, dy = _xf(float(a[1]), float(a[2]), rot) + at = (x + dx, y + dy, float(a[3])) + else: + at = (x, y, 0) + e.append(["property", Q(name), Q(text), ["at", r4(at[0]), r4(at[1]), at[2]]] + _eff(hide=hide)) + + prop("Reference", ref, ref.startswith("#")) + prop("Value", val, not show_value) + prop("Footprint", fp, True) + prop("Datasheet", datasheet if datasheet is not None else (props["Datasheet"][2] if "Datasheet" in props else ""), True) + prop("Description", props["Description"][2] if "Description" in props else "", True) + for k, v in (fields or {}).items(): + prop(k, v, True, (x, y, 0)) + for num in sorted(s.pins): + e.append(["pin", Q(num), ["uuid", uid(self.project, self.path, ref, unit, "pin", num)]]) + e.append(["instances", ["project", Q(self.project), ["path", Q(self.path), ["reference", Q(ref)], ["unit", unit]]]]) + self.items.append(e) + return s + + # ---------- connections ---------- + def _stub(self, sym, num, length=STUB): + x, y, (dx, dy) = sym.pin(num) + ex, ey = r4(x + dx * length), r4(y + dy * length) + if length: + self.wire((x, y), (ex, ey)) + return ex, ey, (dx, dy) + + def wire(self, *pts): + for a, b in zip(pts, pts[1:]): + self.items.append(["wire", ["pts", ["xy", r4(a[0]), r4(a[1])], ["xy", r4(b[0]), r4(b[1])]], + ["stroke", ["width", 0], ["type", "default"]], ["uuid", self._uid("w")]]) + + def junction(self, x, y): + self.items.append(["junction", ["at", r4(x), r4(y)], ["diameter", 0], ["color", 0, 0, 0, 0], + ["uuid", self._uid("j")]]) + + @staticmethod + def _label_at(dx, dy): + """Label angle and justification so the text runs away from the pin.""" + if dx > 0: + return 0, "left bottom" + if dx < 0: + return 180, "right bottom" + if dy < 0: + return 90, "left bottom" + return 270, "right bottom" + + def label(self, name, x, y, dx=1, dy=0): + ang, just = self._label_at(dx, dy) + self.items.append(["label", Q(name), ["at", r4(x), r4(y), ang]] + _eff(just) + [["uuid", self._uid("l", name)]]) + + def net(self, sym, num, name, length=STUB): + """Stub from the pin and a local net label at its end.""" + x, y, (dx, dy) = self._stub(sym, num, length) + self.label(name, x, y, dx, dy) + + def hlabel(self, sym, num, name, shape="input", length=STUB): + x, y, (dx, dy) = self._stub(sym, num, length) + ang, just = self._label_at(dx, dy) + just = just.split()[0] + self.items.append(["hierarchical_label", Q(name), ["shape", shape], ["at", x, y, ang]] + _eff(just) + + [["uuid", self._uid("h", name)]]) + + def global_label(self, name, x, y, ang=0, shape="input"): + just = "left" if ang == 0 else "right" + self.items.append(["global_label", Q(name), ["shape", shape], ["at", r4(x), r4(y), ang]] + _eff(just) + + [["uuid", self._uid("g", name)]]) + + def power(self, sym, num, name, length=STUB): + """Stub from the pin and a power symbol (power:<name>) at its end, turned so that it + points away from the pin (a stub that turned instead could land on the next pin's).""" + x, y, (dx, dy) = self._stub(sym, num, length) + down = name.upper().startswith("GND") or name.startswith("-") + # rotation that turns the symbol's body (down for ground, up for supplies) outward + if down: + rot = {(0, 1): 0, (1, 0): 90, (0, -1): 180, (-1, 0): 270}[(dx, dy)] + else: + rot = {(0, -1): 0, (-1, 0): 90, (0, 1): 180, (1, 0): 270}[(dx, dy)] + self.power_at(name, x, y, rot) + + def power_at(self, name, x, y, rot=0): + self.npwr += 1 + self.add("power:" + name, "#PWR%02d" % self.npwr, x, y, rot, value=name) + + def flag_at(self, x, y): + self.nflg += 1 + self.add("power:PWR_FLAG", "#FLG%02d" % self.nflg, x, y, 0) + + def nc(self, sym, num): + x, y, _ = sym.pin(num) + self.items.append(["no_connect", ["at", x, y], ["uuid", self._uid("nc")]]) + + def nc_at(self, x, y): + self.items.append(["no_connect", ["at", r4(x), r4(y)], ["uuid", self._uid("nc")]]) + + def text(self, s, x, y, size=1.27): + self.items.append(["text", Q(s), ["exclude_from_sim", "no"], ["at", r4(x), r4(y), 0]] + + _eff("left top", size=size) + [["uuid", self._uid("t")]]) + + # ---------- hierarchy ---------- + def sheet(self, name, filename, x, y, w, h, pins, child_uuid, page="2"): + """Sheet symbol on this (root) sheet. pins: [(name, shape)] down the right edge. + Returns {name: (x, y)} of the pin connection points.""" + e = ["sheet", ["at", r4(x), r4(y)], ["size", r4(w), r4(h)], ["exclude_from_sim", "no"], + ["in_bom", "yes"], ["on_board", "yes"], ["dnp", "no"], ["fields_autoplaced", "yes"], + ["stroke", ["width", 0.1524], ["type", "solid"]], ["fill", ["color", 0, 0, 0, 0.0]], + ["uuid", Q(child_uuid)], + ["property", Q("Sheetname"), Q(name), ["at", r4(x), r4(y - 0.635), 0]] + _eff("left bottom"), + ["property", Q("Sheetfile"), Q(filename), ["at", r4(x), r4(y + h + 0.635), 0]] + _eff("left top")] + where = {} + for i, (pn, shape) in enumerate(pins): + px, py = r4(x + w), r4(y + G * (i + 1)) + e.append(["pin", Q(pn), shape, ["at", px, py, 0]] + _eff("right") + [["uuid", uid(child_uuid, "pin", pn)]]) + where[pn] = (px, py) + e.append(["instances", ["project", Q(self.project), ["path", Q(self.path), ["page", Q(page)]]]]) + self.items.append(e) + return where + + # ---------- output ---------- + def write(self, path): + out = ["kicad_sch", ["version", 20250610], ["generator", Q("schgen")], ["generator_version", Q("10.0")], + ["uuid", Q(self.uuid)], ["paper", Q(self.paper)], + ["lib_symbols"] + [self.libsyms[k] for k in sorted(self.libsyms)]] + out += self.items + if not self.sheet_uuid: + out.append(["sheet_instances", ["path", Q("/"), ["page", Q("1")]]]) + with open(path, "w") as f: + f.write(dump(out) + "\n") |
