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-layout.py

#!/usr/bin/env python3
"""Tidy schematic layout, reference-design style.

Reads a built circuit.json, writes data/schematic-placements.json and data/schematic-sheet-sizes.json.
Each chip (3+ pins) becomes the centre of a cluster. Every 2-pin part (R, C, L, D, LED, test point...) is
put next to the chip pin it connects to, standing upright: GND pin at the bottom, supply-rail pin at the top.
Parts hanging off another 2-pin part (RC compensation, divider chains) go in the next column out.
Clusters are packed left-to-right in signal-flow order (optional per-sheet order below), wrapped onto A4/A3.

usage: python3 tools/sch-layout.py dist/index/circuit.json
"""
import json, math, sys, collections

MM_PER_UNIT = 10.16 / 1.1
SIZES = [("a4", 297, 210), ("a3", 420, 297), ("a2", 594, 420)]
COL = 1.6       # column pitch for upright parts (symbol + value text)
ROW = 1.5       # row pitch for parts above / below a chip
GAP = 2.4       # gap between clusters
MARGIN = 2.2    # sheet inner margin (frame + title strip), units

# Optional signal-flow order of chips per sheet (left -> right, then wrap). Unlisted chips follow by old x.
ORDER = {
    "power_input": ["JPD", "UPDIN", "UIN", "QINKILL", "U5V", "UAON"],
    "usb_hub": ["YHUB", "UHUB"],
    # "|" starts a new row. PD OUT: the converter with its two transistors, the enable gate and the discharge switch
    # on top; underneath the way out: eFuse -> CC protection -> socket.
    "pd_out_": ["QP?H", "QP?L", "UP?BB", "UP?AND", "QP?DIS", "|", "UP?EF", "UP?CC", "JOUT?"],
    # one port after another: 5 V switch -> ESD protection -> socket
    "usb_ports": ["UUSB1PWR", "UUSB1ESD", "JUSB1", "UUSB2PWR", "UUSB2ESD", "JUSB2", "|",
                  "UUSB3PWR", "UUSB3ESD", "JUSB3", "UUSB4PWR", "UUSB4ESD", "JUSB4", "|",
                  "UCAMPWR", "UCAMESD", "JCAM", "UPCESD", "JPC"],
}

# Where each part sits on the BOARD (mm). A supply capacitor is drawn at the chip it is next to on the board.
# Give a full build once with --pcb <circuit.json>; the positions are kept in data/board-positions.json.
BOARD = {}
if "--pcb" in sys.argv:
    k = sys.argv.index("--pcb")
    pj = json.load(open(sys.argv[k + 1])); del sys.argv[k:k + 2]
    names = {e["source_component_id"]: e["name"] for e in pj if e["type"] == "source_component"}
    BOARD = {names[e["source_component_id"]]: [round(e["center"]["x"], 2), round(e["center"]["y"], 2)]
             for e in pj if e["type"] == "pcb_component" and e.get("source_component_id") in names}
    json.dump(BOARD, open("data/board-positions.json", "w"), indent=0, sort_keys=True)
else:
    try:
        BOARD = json.load(open("data/board-positions.json"))
    except FileNotFoundError:
        pass
def board_dist(a, b):
    return math.dist(BOARD[a], BOARD[b]) if a in BOARD and b in BOARD else 1e3

cj = json.load(open(sys.argv[1]))
by = collections.defaultdict(list)
for e in cj:
    by[e["type"]].append(e)
src = {e["source_component_id"]: e for e in by["source_component"]}
sheets = {e["schematic_sheet_id"]: e["name"] for e in by["schematic_sheet"]}
old = json.load(open("data/schematic-placements.json"))

# ---- nets: union-find over source ports and source nets
parent = {}
def find(a):
    parent.setdefault(a, a)
    while parent[a] != a:
        parent[a] = parent[parent[a]]
        a = parent[a]
    return a
def union(a, b):
    parent[find(a)] = find(b)
for t in by["source_trace"]:
    ids = t.get("connected_source_port_ids", []) + t.get("connected_source_net_ids", [])
    for x in ids[1:]:
        union(ids[0], x)
netname = {}
for n in by["source_net"]:
    netname[find(n["source_net_id"])] = n["name"]
def net_of(sp):
    r = find(sp)
    return r
deg = collections.Counter(net_of(p["source_port_id"]) for p in by["source_port"])
def nname(r):
    return netname.get(r, r)
def is_gnd(r):
    return "GND" in nname(r).upper()
def is_rail(r):
    nm = nname(r).upper()
    return is_gnd(r) or deg[r] >= 8 or nm.startswith("V") and any(ch.isdigit() for ch in nm)

# ---- components
ports = collections.defaultdict(list)
for p in by["schematic_port"]:
    ports[p["schematic_component_id"]].append(p)

def rot_pt(x, y, deg_):
    a = math.radians(deg_)
    return x * math.cos(a) - y * math.sin(a), x * math.sin(a) + y * math.cos(a)

comps = {}
for c in by["schematic_component"]:
    s = src[c["source_component_id"]]
    ps = ports[c["schematic_component_id"]]
    cx, cy = c["center"]["x"], c["center"]["y"]
    name = s["name"]
    cur_rot = (old.get(name) or {}).get("schRotation", c.get("rotation", 0)) or 0
    pl = []
    for p in ps:
        dx, dy = p["center"]["x"] - cx, p["center"]["y"] - cy
        pl.append(dict(num=p.get("pin_number"), dx=dx, dy=dy, net=net_of(p["source_port_id"]),
                       side=p.get("side_of_component") or ("left" if dx < -0.05 else "right" if dx > 0.05 else "bottom" if dy < 0 else "top")))
    w, h = c["size"]["width"], c["size"]["height"]
    xs = [0] + [p["dx"] for p in pl]; ys = [0] + [p["dy"] for p in pl]
    comps[name] = dict(name=name, sheet=sheets.get(c.get("schematic_sheet_id")), ports=pl, rot=cur_rot,
                       small=len(pl) <= 2, w=w, h=h, ox=cx, oy=cy,
                       box=(min(-w / 2, min(xs)), min(-h / 2, min(ys)), max(w / 2, max(xs)), max(h / 2, max(ys))))

placements, sizes = {}, {}

def upright_rot(c, top_net):
    """Rotation that puts the pin on `top_net` at the top (2-pin parts)."""
    p1 = next((p for p in c["ports"] if p["num"] == 1), c["ports"][0])
    # base (rotation 0) offset of pin 1
    bx, by_ = rot_pt(p1["dx"], p1["dy"], -c["rot"])
    want_pin1_top = p1["net"] == top_net
    for r in (0, 90, 180, 270):
        x, y = rot_pt(bx, by_, r)
        if abs(x) < 0.05 and ((y > 0) == want_pin1_top):
            return r
    return c["rot"]

def flat_rot(c, left_net):
    """Rotation that lays a 2-pin part flat with the pin on `left_net` at the left."""
    p1 = next((p for p in c["ports"] if p["num"] == 1), c["ports"][0])
    bx, by_ = rot_pt(p1["dx"], p1["dy"], -c["rot"])
    want_pin1_left = p1["net"] == left_net
    for r in (0, 90, 180, 270):
        x, y = rot_pt(bx, by_, r)
        if abs(y) < 0.05 and ((x < 0) == want_pin1_left):
            return r
    return c["rot"]

for sheet in sorted(set(c["sheet"] for c in comps.values() if c["sheet"])):
    members = [c for c in comps.values() if c["sheet"] == sheet]
    chips = [c for c in members if not c["small"]]
    smalls = [c for c in members if c["small"]]
    chip_ports = collections.defaultdict(list)  # net -> [(chip, port)]
    for ch in chips:
        for p in ch["ports"]:
            chip_ports[p["net"]].append((ch, p))
    # anchor each small part to a chip port; prefer signal nets, then rails (non-GND), spread rail caps
    anchor = {}
    rail_use = collections.Counter()
    def anchor_to_chip(s, allow_gnd):
        nets = [p["net"] for p in s["ports"]]
        has_signal = any(not is_rail(n) for n in nets)
        cands = []
        for n in nets:
            for ch, p in chip_ports.get(n, []):
                pri = 0 if not is_rail(n) else (2 if is_gnd(n) else 1)
                # a part with a signal end sits where that signal goes; some chip's ground pin is the last resort
                if pri == 2 and has_signal and not allow_gnd:
                    continue
                # a part sits at its most specific net (a divider at the pin it feeds, not at the busy output node)
                # on a supply net: the chip it is next to on the board (a decoupling capacitor belongs to that chip)
                near = round(board_dist(s["name"], ch["name"]), 1)
                cands.append((pri, (0, near, rail_use[(ch["name"], p["num"])]) if pri else (deg[n], near, 0), ch["name"], p["num"], ch, p))
        if cands:
            cands.sort(key=lambda t: t[:4])
            pri, _, _, _, ch, p = cands[0]
            if pri:
                rail_use[(ch["name"], p["num"])] += 1
            anchor[s["name"]] = (ch["name"], p, p["net"])
    for s in sorted(smalls, key=lambda s: s["name"]):
        anchor_to_chip(s, False)
    # second level: hang off an anchored small part through a shared signal net
    for _ in range(4):
        for s in smalls:
            if s["name"] in anchor:
                continue
            for p in s["ports"]:
                if is_rail(p["net"]):
                    continue
                hit = next((o for o in smalls if o["name"] in anchor and o is not s and any(q["net"] == p["net"] for q in o["ports"])), None)
                if hit:
                    ch, cp, _ = anchor[hit["name"]]
                    anchor[s["name"]] = (ch, cp, p["net"], hit["name"])
                    break

    for s in sorted(smalls, key=lambda s: s["name"]):
        if s["name"] not in anchor:
            anchor_to_chip(s, True)

    # ---- build clusters around each chip (coordinates relative to chip centre)
    clusters = []
    for ch in chips:
        x0, y0, x1, y1 = ch["box"]
        items = [(ch["name"], 0.0, 0.0, None)]
        mine = [s for s in smalls if s["name"] in anchor and anchor[s["name"]][0] == ch["name"]]
        occupied = collections.defaultdict(list)  # (side, col) -> [(lo, hi)]
        def free(side, col, lo, hi):
            return all(hi <= a or lo >= b for a, b in occupied[(side, col)])
        # order: first-level parts by pin position, then their children
        def key(s):
            a = anchor[s["name"]]
            return (len(a) > 3, -a[1]["dy"] if a[1]["side"] in ("left", "right") else a[1]["dx"], s["name"])
        pos = {}
        for s in sorted(mine, key=key):
            a = anchor[s["name"]]
            p = a[1]
            side = p["side"]
            nets = [q["net"] for q in s["ports"]]
            other = [n for n in nets if n != a[2]]
            gnd = next((n for n in nets if is_gnd(n)), None)
            rail = next((n for n in nets if is_rail(n) and not is_gnd(n)), None)
            if len(s["ports"]) == 1:
                rot = s["rot"]
            elif gnd is not None:
                rot = upright_rot(s, next(n for n in nets if n != gnd) if len(set(nets)) > 1 else nets[0])
            elif rail is not None:
                rot = upright_rot(s, rail)
            else:
                rot = upright_rot(s, a[2])
            hh = 0.95
            start = 1 if len(a) <= 3 else (pos[a[3]][2] + 1 if a[3] in pos else 2)
            # both ends on two pins of the same side of this chip: lie across the two pins
            span = None
            if len(a) <= 3 and len(s["ports"]) == 2 and len(set(nets)) == 2:
                q = [next((cp for cp in ch["ports"] if cp["net"] == n and cp["side"] == side), None) for n in nets]
                if all(q) and not any(is_gnd(n) or nname(n).upper().startswith("V") for n in nets):
                    span = q
            if span and side in ("top", "bottom"):
                first = min(span, key=lambda cp: cp["dx"])          # pin on the left
                rot = flat_rot(s, first["net"])
                want = (span[0]["dx"] + span[1]["dx"]) / 2
                row = 1
                while not free(side, row, want - 0.8, want + 0.8):
                    row += 1
                occupied[(side, row)].append((want - 0.8, want + 0.8))
                edge = y1 if side == "top" else y0
                sgn = 1 if side == "top" else -1
                pos[s["name"]] = (want, edge + sgn * (1.5 + (row - 1) * ROW), row, rot)
                continue
            if side in ("left", "right"):
                want = p["dy"]
                col = start
                while True:
                    lo, hi = want - hh, want + hh
                    if free(side, col, lo, hi):
                        break
                    # try sliding a little before moving out a column
                    moved = False
                    for d in (0.6, -0.6, 1.2, -1.2):
                        if free(side, col, lo + d, hi + d):
                            want += d; moved = True; break
                    if moved:
                        break
                    col += 1
                occupied[(side, col)].append((want - hh, want + hh))
                edge = x0 if side == "left" else x1
                sgn = -1 if side == "left" else 1
                x = edge + sgn * (2.1 + (col - 1) * COL)
                pos[s["name"]] = (x, want, col, rot)
            else:
                want = p["dx"]
                row = start
                while not free(side, row, want - 0.6, want + 0.6):
                    ok = False
                    for d in (0.7, -0.7, 1.4, -1.4):
                        if free(side, row, want - 0.6 + d, want + 0.6 + d):
                            want += d; ok = True; break
                    if ok:
                        break
                    row += 1
                occupied[(side, row)].append((want - 0.6, want + 0.6))
                edge = y1 if side == "top" else y0
                sgn = 1 if side == "top" else -1
                y = edge + sgn * (1.5 + (row - 1) * ROW)
                pos[s["name"]] = (want, y, row, rot)
        for nm, (x, y, _, rot) in pos.items():
            items.append((nm, x, y, rot))
        clusters.append(dict(chip=ch, items=items))
    loose = [s for s in smalls if s["name"] not in anchor or not any(s["name"] == it[0] for cl in clusters for it in cl["items"])]
    if loose:
        loose.sort(key=lambda s: s["name"])
        n = len(loose); per = max(1, math.ceil(math.sqrt(n * 2)))
        items = []
        for i, s in enumerate(loose):
            nets = [p["net"] for p in s["ports"]]
            gnd = next((x for x in nets if is_gnd(x)), None)
            rot = s["rot"] if len(s["ports"]) < 2 else upright_rot(s, next((x for x in nets if x != gnd), nets[0]))
            items.append((s["name"], (i % per) * COL, -(i // per) * 1.6, rot))
        clusters.append(dict(chip=None, items=items))

    # cluster bounding boxes
    def ext(nm, x, y):
        c = comps[nm]
        if c["small"]:
            return (x - 0.45, y - 0.6, x + 1.0, y + 0.6)  # value text on the right
        b = c["box"]
        return (x + b[0] - 0.5, y + b[1] - 0.35, x + b[2] + 0.5, y + b[3] + 0.45)
    for cl in clusters:
        bs = [ext(nm, x, y) for nm, x, y, _ in cl["items"]]
        cl["bb"] = (min(b[0] for b in bs), min(b[1] for b in bs), max(b[2] for b in bs), max(b[3] for b in bs))
    # order clusters
    order = ORDER.get(sheet)
    if order is None:
        for k, v in ORDER.items():
            if k.endswith("_") and sheet.startswith(k):
                num = sheet[len(k):]
                order = [x.replace("?", num) for x in v]
    def okey(cl):
        if cl["chip"] is None:
            return (2, 0, 0)
        nm = cl["chip"]["name"]
        if order and nm in order:
            return (0, order.index(nm), 0)
        return (1, round(cl["chip"]["ox"], 1), -cl["chip"]["oy"])
    clusters.sort(key=okey)
    breaks = set()
    if order:
        breaks = {order[k + 1] for k, x in enumerate(order[:-1]) if x == "|"}
    for cl in clusters:
        cl["brk"] = bool(cl["chip"]) and cl["chip"]["name"] in breaks
    total_w = sum(cl["bb"][2] - cl["bb"][0] + GAP for cl in clusters)
    total_area = sum((cl["bb"][2] - cl["bb"][0] + GAP) * (cl["bb"][3] - cl["bb"][1] + GAP) for cl in clusters)
    # pick the smallest sheet that fits with shelf packing; close the gaps a little before going a size up
    fitted = False
    for sname, wmm, hmm in SIZES:
        for gap in (GAP, 2.0, 1.7):
            W, H = wmm / MM_PER_UNIT - 2 * MARGIN, hmm / MM_PER_UNIT - 2 * MARGIN
            rows, cur, cw = [], [], 0
            for cl in clusters:
                bw = cl["bb"][2] - cl["bb"][0]
                if cur and (cw + gap + bw > W or cl["brk"]):
                    rows.append(cur); cur, cw = [], 0
                cur.append(cl); cw += (gap if cw else 0) + bw
            if cur:
                rows.append(cur)
            rh = [max(cl["bb"][3] - cl["bb"][1] for cl in r) for r in rows]
            if sum(rh) + gap * (len(rows) - 1) <= H and all(cl["bb"][2] - cl["bb"][0] <= W for cl in clusters):
                fitted = True
                break
        if fitted:
            break
    GAP_ = gap
    sizes[sheet] = {"width": wmm, "height": hmm}
    tot_h = sum(rh) + GAP_ * (len(rows) - 1)
    ytop = tot_h / 2
    for r, h_ in zip(rows, rh):
        rw = sum(cl["bb"][2] - cl["bb"][0] for cl in r) + GAP_ * (len(r) - 1)
        xl = -rw / 2
        for cl in r:
            bx0, by0, bx1, by1 = cl["bb"]
            ox = xl - bx0
            oy = ytop - (h_ - (by1 - by0)) / 2 - by1   # centre vertically in the row
            for nm, x, y, rot in cl["items"]:
                pl = {"schX": round(ox + x, 3), "schY": round(oy + y, 3)}
                rr = comps[nm]["rot"] if rot is None else rot
                pl["schRotation"] = rr
                for k in ("schWidth", "schHeight"):          # box sizes from tools/sch-chip-sizes.py
                    if old.get(nm, {}).get(k):
                        pl[k] = old[nm][k]
                placements[nm] = pl
            xl += bx1 - bx0 + GAP_
        ytop -= h_ + GAP_
    print(f"{sheet:14s} {len(members):3d} parts {len(clusters):2d} clusters -> {sname}")
    if sheet in sys.argv[2:]:      # extra argument: sheet names to show cluster sizes for
        for cl in clusters:
            print("     ", cl["chip"]["name"] if cl["chip"] else "(loose)", "%.1f x %.1f" % (cl["bb"][2] - cl["bb"][0], cl["bb"][3] - cl["bb"][1]))

missing = [n for n in old if n not in placements]
for n in missing:          # parts not in this build keep their old entry
    placements[n] = old[n]
json.dump(placements, open("data/schematic-placements.json", "w"), indent=2)
json.dump(sizes, open("data/schematic-sheet-sizes.json", "w"), indent=2)
print("wrote", len(placements), "placements;", len(missing), "kept from old file")