MustafaMulla29/usb-pd-motherboard

4-layer USB-C PD hub motherboard with 20 V USB-C input, Linux T113-S3 computer, CH338F USB hub, four individually controlled 5–20 V PD outputs, USB data/camera ports, regulated rails, and hardware watchdog/E-stop safety interlock.

Version
1.0.24
License
unset
Stars
0

Use with the tscircuit CLI

tsci is the tscircuit CLI. Install it with npm install -g tscircuit.

tsci clone MustafaMulla29/usb-pd-motherboard  # download the package files into ./usb-pd-motherboard
tsci add MustafaMulla29/usb-pd-motherboard    # add it to your project as @tsci/MustafaMulla29.usb-pd-motherboard

In a cloned or new (tsci init) project: tsci dev starts a local preview, tsci build outputs Circuit JSON, and tsci push publishes to tscircuit.com.

tools/sch-notes.py

#!/usr/bin/env python3
"""Titles, section labels and reference notes for the schematic sheets.

  SCH_ONLY=1 bun tools/build-schematic.ts && python3 -I tools/sch-notes.py && SCH_ONLY=1 bun tools/build-schematic.ts

Reads  dist/codex-schematic.circuit.json   where every part sits on its sheet (run tools/sch-layout.py first)
       data/schematic-notes-content.json   the wording: per sheet, a label for each chip and the notes
Writes data/schematic-notes.json           every text with its position (circuit/schematic-notes.tsx draws them)
       data/schematic-sheet-sizes.json     a sheet is made larger if its title and notes would not fit
A section label goes above the cluster of parts around its chip, the title above everything, the notes below.
"""
import json, math, collections, re
cj = json.load(open("dist/codex-schematic.circuit.json"))
content = json.load(open("data/schematic-notes-content.json"))
sizes = json.load(open("data/schematic-sheet-sizes.json"))
MM = 10.16 / 1.1; MARGIN = 2.2; CH = 0.58          # mm per schematic unit; sheet margin; text width per character / font size
SIZES = [(297, 210), (420, 297), (594, 420)]
src = {e["source_component_id"]: e["name"] for e in cj if e["type"] == "source_component"}
sheets = sorted((e for e in cj if e["type"] == "schematic_sheet"), key=lambda e: e.get("sheet_index", 0))
nports = collections.Counter(e["schematic_component_id"] for e in cj if e["type"] == "schematic_port")
def box(e):
    c = e.get("center") or {"x": 0, "y": 0}; s = e.get("size") or {"width": 0.6, "height": 0.6}
    return [c["x"] - s["width"] / 2, c["y"] - s["height"] / 2, c["x"] + s["width"] / 2, c["y"] + s["height"] / 2]
def grow(a, b): return [min(a[0], b[0]), min(a[1], b[1]), max(a[2], b[2]), max(a[3], b[3])]
out = {}; N = len(sheets)
for k, sh in enumerate(sheets):
    name = sh["name"]; sid = sh["schematic_sheet_id"]
    if name == "guide": continue
    spec = content.get(name) or content.get(re.sub(r"\d+$", "N", name)) or {"sections": {}, "notes": []}
    port_no = (re.search(r"(\d+)$", name) or [None, ""])[1]
    comps = [e for e in cj if e["type"] == "schematic_component" and e.get("schematic_sheet_id") == sid and "NOTES_" not in src.get(e["source_component_id"], "")]
    if not comps: continue
    extra = [e for e in cj if e["type"] in ("schematic_net_label", "schematic_trace") and e.get("schematic_sheet_id") == sid]
    pts = []
    for e in extra:
        if e["type"] == "schematic_net_label": pts.append((e["center"]["x"], e["center"]["y"]))
        else:
            for ed in e.get("edges", []): pts += [(ed["from"]["x"], ed["from"]["y"]), (ed["to"]["x"], ed["to"]["y"])]
    boxes = {src[e["source_component_id"]]: box(e) for e in comps}
    chips = [src[e["source_component_id"]] for e in comps if nports[e["schematic_component_id"]] >= 3]
    cluster = {c: list(boxes[c]) for c in chips}
    cen = lambda b: ((b[0] + b[2]) / 2, (b[1] + b[3]) / 2)
    for n, b in boxes.items():
        if n in cluster or not chips: continue
        near = min(chips, key=lambda c: math.dist(cen(b), cen(boxes[c])))
        cluster[near] = grow(cluster[near], b)
    for c in cluster:                                   # wires and net labels that hang on the cluster
        b = cluster[c]; pad = 0.9
        for x, y in pts:
            if b[0] - pad <= x <= b[2] + pad and b[1] - pad <= y <= b[3] + pad: cluster[c] = grow(cluster[c], [x, y, x, y])
    allb = None
    for b in list(boxes.values()) + [[x, y, x, y] for x, y in pts]: allb = b if allb is None else grow(allb, b)
    texts = []; base = list(allb)
    # everything a label must stay clear of: parts, their texts, net labels, wires
    obst = [[b[0] - 0.15, b[1] - 0.15, b[2] + 0.15, b[3] + 0.15] for b in boxes.values()]
    wires = []
    # a 2-pin part's name and value are written to its right; a chip's name sits above its box
    for e in comps:
        b = boxes[src[e["source_component_id"]]]
        obst.append([b[2], b[1] - 0.1, b[2] + 1.1, b[3] + 0.1] if nports[e["schematic_component_id"]] < 3 else [b[0], b[3], b[2] + 1.6, b[3] + 0.45])
    comp_ids = {e["schematic_component_id"] for e in comps}
    for e in cj:
        if e.get("schematic_sheet_id") != sid and e.get("schematic_component_id") not in comp_ids: continue
        if e["type"] == "schematic_text":
            fs = e.get("font_size", 0.18); w = len(e.get("text", "")) * fs * 0.62; x, y = e["position"]["x"], e["position"]["y"]; a = e.get("anchor", "center")
            x0 = x if "left" in a else x - w if "right" in a else x - w / 2
            obst.append([x0, y - fs * 0.7, x0 + w, y + fs * 0.7])
        elif e["type"] == "schematic_net_label":
            w = len(e.get("text", "")) * 0.18 * 0.62 + 0.35; x, y = e["center"]["x"], e["center"]["y"]
            obst.append([x - w, y - 0.22, x + w, y + 0.22] if e.get("anchor_side") in ("left", "right") else [x - 0.22, y - w, x + 0.22, y + w])
        elif e["type"] == "schematic_trace":
            for ed in e.get("edges", []): wires.append([min(ed["from"]["x"], ed["to"]["x"]) - 0.08, min(ed["from"]["y"], ed["to"]["y"]) - 0.08, max(ed["from"]["x"], ed["to"]["x"]) + 0.08, max(ed["from"]["y"], ed["to"]["y"]) + 0.08])
    def free(x, y, w, fs, also_wires=True): return not any(x - 0.1 < o[2] and o[0] < x + w + 0.1 and y - fs * 0.75 < o[3] and o[1] < y + fs * 0.75 for o in (obst + wires if also_wires else obst))
    # section labels
    placed = []
    for pat, label in spec["sections"].items():
        cname = pat.replace("?", port_no)
        if cname not in cluster: print(f"  {name}: no chip {cname} for label {label!r}"); continue
        b = cluster[cname]; label = label.replace("?", port_no)
        w = len(label) * 0.3 * 0.62; best = None
        cb = boxes[cname]                                            # right above the chip itself, not the whole cluster
        # A label must stay with its own chip: above it, no higher than just over the chip's own group of parts;
        # else below it; only then further up. Never over a part, a text or a wire; never wider than the drawing.
        clash = lambda x, y: any(abs(y - py) < 0.45 and x < px + pw + 0.3 and px < x + w + 0.3 for px, py, pw in placed)
        clampx = lambda x: min(max(x, base[0]), max(base[0], base[2] - w))
        steps = lambda reach: [0.4 + 0.15 * i for i in range(0, int(reach / 0.15) + 1)]
        for side, reach in ((1, b[3] - cb[3] + 1.6), (-1, cb[1] - b[1] + 1.6), (1, 9.0)):
            for dy in steps(reach):
                for dx in (0, -0.5, 0.5, -1.2, 1.2, -2.2, 2.2, -3.4, 3.4):
                    x, y = clampx(cb[0] + dx), (cb[3] + dy if side > 0 else cb[1] - dy)
                    if free(x, y, w, 0.3) and not clash(x, y): best = (x, y); break
                if best: break
            if best: break
        x, y = best or (cb[0], b[3] + 0.6)
        obst.append([x, y - 0.2, x + w, y + 0.2])
        placed.append((x, y, w)); texts.append({"text": label, "x": round(x, 3), "y": round(y, 3), "fontSize": 0.3, "anchor": "left"})
        allb = grow(allb, [x, y - 0.2, x + w, y + 0.2])
    # title and notes, centred on the drawing so the sheet frame stays centred
    title = f"{k + 1} / {N} — {re.sub(r'^[0-9]+ ', '', sh.get('display_name') or name)}"
    notes = spec["notes"]; nw = max([len(t) * 0.23 * CH for t in notes] + [len(title) * 0.42 * CH])
    cx = (allb[0] + allb[2]) / 2; x0 = min(allb[0], cx - nw / 2)
    ty = allb[3] + 1.5
    texts.append({"text": title, "x": round(x0, 3), "y": round(ty, 3), "fontSize": 0.42, "anchor": "left"})
    for i, t in enumerate(notes):
        texts.append({"text": t.replace("?", port_no) if "pd_out" in name else t, "x": round(x0, 3), "y": round(allb[1] - 1.3 - 0.45 * i, 3), "fontSize": 0.23, "anchor": "left"})
    full = [min(allb[0], x0), allb[1] - 1.3 - 0.45 * len(notes), max(allb[2], x0 + nw), ty + 0.4]
    need_w = (full[2] - full[0] + 2 * MARGIN) * MM; need_h = (full[3] - full[1] + 2 * MARGIN) * MM
    w, h = next(((w, h) for w, h in SIZES if w * 1.04 >= need_w and h * 1.04 >= need_h), SIZES[-1])   # 4 % into the margin is fine
    if (w, h) != (sizes[name]["width"], sizes[name]["height"]): print(f"  {name}: sheet {sizes[name]['width']} x {sizes[name]['height']} -> {w} x {h} mm")
    sizes[name] = {"width": w, "height": h}
    out[name] = texts
    print(f"{name:14s} {len(texts):3d} texts, drawing {full[2] - full[0]:.1f} x {full[3] - full[1]:.1f} units")
json.dump(out, open("data/schematic-notes.json", "w"), indent=1, ensure_ascii=False)
json.dump(sizes, open("data/schematic-sheet-sizes.json", "w"), indent=2)