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/router/reroute.py

"""Re-route a few nets and leave every other trace exactly where it is.

  python3 -I tools/router/reroute.py VDD_DDR [MORE_NETS...] [--keep NET,NET] [--neck 15] [--time 120]

Needs routing/inputs/ALL.fr.txt from the last dump (ROUTE_DUMP=1 tsci build ..., then tools/router/prep.py).
The copper of all other nets goes to the router as fixed obstacles, so the named nets have to find room
around it; nothing else is ripped. --neck makes narrow sections of wide nets dearer (default 15: a power
net takes a detour or two vias rather than squeeze through at 0.1 mm). On success ALL.routed.json is
updated in place; the previous file is kept as routing/inputs/ALL.routed.before-reroute.json.

Named nets are routed again from scratch. Nets given with --keep keep the copper they have (used for the
big shared nets when parts were swapped: GND, V3V3): only what no longer fits is taken out, namely routes that
start or end on a pad that is gone, routes that now touch a pad of another net (a new part put where the copper
ran), and routes that hung on such a route; then only the pins left without a connection get new copper.
Routes of nets that no longer exist are dropped.
A route of any OTHER net that starts or ends on a pad that is gone, or touches a pad of another net, stops the
run: name that net too.
"""
import json, math, os, shutil, subprocess, sys
args = [a for a in sys.argv[1:]]
def opt(name, default):
    if name in args: i = args.index(name); v = args[i + 1]; del args[i:i + 2]; return v
    return default
neck = opt("--neck", "15"); tlimit = opt("--time", "120")
keep = [k for k in opt("--keep", "").split(",") if k]
want = args
if not want and not keep: sys.exit(__doc__)
lines = open("routing/inputs/ALL.fr.txt").read().splitlines()
L = next(l.split()[1:] for l in lines if l.startswith("L "))
RL = [int(k) for k in next(l.split()[1:] for l in lines if l.startswith("RL "))]
idx = {l.split()[2]: int(l.split()[1]) for l in lines if l.startswith("N ")}
missing = [n for n in want + keep if n not in idx]
if missing: sys.exit(f"unknown net(s): {missing}")
key = lambda x, y: (round(x * 1e3), round(y * 1e3))
pin_at = {}; fixed_via = {}; pad_grid = {}
npin = 0
for l in lines:
    t = l.split()
    if t[0] == "PIN": pin_at[(int(t[1]), key(float(t[2]), float(t[3])))] = npin; npin += 1
    elif t[0] == "PAD":
        if t[7] == "2" and int(t[1]) >= 0: fixed_via.setdefault(int(t[1]), []).append((float(t[3]), float(t[4])))
        pad = (int(t[1]), int(t[2]), float(t[3]), float(t[4]), float(t[5]), float(t[6]), t[8] == "1" or t[7] == "2")
        for gx in range(int((pad[2] - pad[4] / 2 - 1) // 2), int((pad[2] + pad[4] / 2 + 1) // 2) + 1):
            for gy in range(int((pad[3] - pad[5] / 2 - 1) // 2), int((pad[3] + pad[5] / 2 + 1) // 2) + 1): pad_grid.setdefault((gx, gy), []).append(pad)
routed = json.load(open("routing/ALL.routed.json"))
shutil.copy("routing/ALL.routed.json", "routing/inputs/ALL.routed.before-reroute.json")

# ---- what stays of the saved copper ----
gone = [r for r in routed if r["net"] not in idx]
routed = [r for r in routed if r["net"] in idx]
def end_ok(r, e): return r[e] is None or (idx[r["net"]], key(r[e]["x"], r[e]["y"])) in pin_at
stale = {}
for r in routed:
    if r["net"] in want: continue
    if not (end_ok(r, "from") and end_ok(r, "to")): stale.setdefault(r["net"], []).append(r)
def touches_pad(r):
    """Does the route's copper come closer than the 0.1 mm rule to a pad of another net (as the board is now)?"""
    n = idx[r["net"]]; pts = r["route"]
    def near(x, y, mask, rad):
        for pd in pad_grid.get((int(x // 2), int(y // 2)), []):
            if pd[0] == n or not (pd[1] & mask): continue
            if pd[6]: d = math.hypot(x - pd[2], y - pd[3]) - pd[4] / 2
            elif pd[1] == 15:        # plated hole: round or pill-shaped (the router's file gives only its bounding box)
                rr = min(pd[4], pd[5]) / 2; d = math.hypot(max(abs(x - pd[2]) - (pd[4] / 2 - rr), 0), max(abs(y - pd[3]) - (pd[5] / 2 - rr), 0)) - rr
            else: d = math.hypot(max(abs(x - pd[2]) - pd[4] / 2, 0), max(abs(y - pd[3]) - pd[5] / 2, 0))
            if d < rad + 0.1 - 0.004: return True
        return False
    for p in pts:
        if p["route_type"] == "via" and near(p["x"], p["y"], 15, 0.225): return True
    for a, b in zip(pts, pts[1:]):
        if not (a["route_type"] == "wire" and b["route_type"] == "wire" and a["layer"] == b["layer"]): continue
        mask = 1 << L.index(a["layer"]); hw = max(a["width"], b["width"]) / 2; ln = math.hypot(b["x"] - a["x"], b["y"] - a["y"]); k = max(1, int(ln / 0.04))
        for i in range(k + 1):
            if near(a["x"] + (b["x"] - a["x"]) * i / k, a["y"] + (b["y"] - a["y"]) * i / k, mask, hw): return True
    return False
for r in routed:
    if r["net"] in want or any(r is q for q in stale.get(r["net"], [])): continue
    if touches_pad(r): stale.setdefault(r["net"], []).append(r)
blocked = sorted(n for n in stale if n not in keep)
if blocked: sys.exit(f"saved routes of these nets start or end on a pad that is gone, or touch a pad of another net: {blocked}\nname them (to route them again) or add them to --keep")
dropped = {n: len(v) for n, v in stale.items()}
dead = {id(r) for v in stale.values() for r in v}
def seg_dist(px, py, a, b):
    vx, vy = b["x"] - a["x"], b["y"] - a["y"]; L2 = vx * vx + vy * vy
    t = 0 if L2 == 0 else max(0, min(1, ((px - a["x"]) * vx + (py - a["y"]) * vy) / L2))
    return math.hypot(px - (a["x"] + t * vx), py - (a["y"] + t * vy))
def on_copper(p, others):
    """Is point p of a route on copper of one of `others` (same net)?"""
    for q in others:
        pts = q["route"]
        for u in pts:
            if u["route_type"] == "via" and math.hypot(u["x"] - p["x"], u["y"] - p["y"]) <= 0.03: return True
        if p["route_type"] == "via": continue
        for u, v in zip(pts, pts[1:]):
            if u["route_type"] == "wire" and v["route_type"] == "wire" and u["layer"] == v["layer"] == p["layer"] and seg_dist(p["x"], p["y"], u, v) <= 0.03: return True
    return False
def on_fixed_via(net, p): return any(math.hypot(x - p["x"], y - p["y"]) <= 0.03 for x, y in fixed_via.get(idx[net], []))
def plane_end(r):
    last = r["route"][-1]
    return r["to"] is None and last["route_type"] == "via" and L.index(last["to_layer"]) not in RL
changed = True
while changed:                       # routes that hung on a route that is gone go too
    changed = False
    for n in keep:
        mine = [r for r in routed if r["net"] == n and id(r) not in dead]
        for r in mine:
            others = [q for q in mine if q is not r and id(q) not in dead]
            pts = r["route"]; bad = False
            if r["from"] is None and not (on_copper(pts[0], others) or (len(pts) > 1 and on_copper(pts[1], others)) or on_fixed_via(n, pts[0])): bad = True
            if r["to"] is None and not plane_end(r) and not (on_copper(pts[-1], others) or (len(pts) > 1 and on_copper(pts[-2], others)) or on_fixed_via(n, pts[-1])): bad = True
            if bad: dead.add(id(r)); dropped[n] = dropped.get(n, 0) + 1; changed = True
routed = [r for r in routed if id(r) not in dead]
if gone or dropped:
    from collections import Counter
    print(f"dropped {len(gone)} route(s) of nets that no longer exist {dict(Counter(r['net'] for r in gone))}; routes taken out of kept nets: {dropped}")
json.dump(routed, open("routing/ALL.routed.json", "w"), separators=(",", ":"))

# ---- router input ----
extra = []
for r in routed:
    if r["net"] in want: continue
    n = idx[r["net"]]; pts = r["route"]
    if r["net"] in keep:
        a = pin_at[(n, key(r["from"]["x"], r["from"]["y"]))] if r["from"] else -1
        b = pin_at[(n, key(r["to"]["x"], r["to"]["y"]))] if r["to"] else -1
        plane = 1 if (plane_end(r) or (r["to"] is None and pts[-1]["route_type"] == "wire" and on_fixed_via(r["net"], pts[-1]))) else 0
        extra.append(f"KT {n} {a} {b} {plane} {len(pts)}")
        for p in pts:
            if p["route_type"] == "via":
                li = L.index(p["to_layer"]); extra.append(f"kv {p['x']} {p['y']} {li if li in RL else -1}")
            else: extra.append(f"kw {p['x']} {p['y']} {L.index(p['layer'])} {p['width']}")
        continue
    for a, b in zip(pts, pts[1:]):
        if a["route_type"] == "wire" and b["route_type"] == "wire" and a["layer"] == b["layer"]:
            extra.append(f"FIX {n} {L.index(a['layer'])} {a['x']} {a['y']} {b['x']} {b['y']} {max(a['width'], b['width'])}")
    extra += [f"FIXV {n} {p['x']} {p['y']}" for p in pts if p["route_type"] == "via"]
extra.append("ONLY " + " ".join(str(idx[n]) for n in want + keep))
open("routing/inputs/PART.fr.txt", "w").write("\n".join(lines + extra) + "\n")
if not os.environ.get("FR_NOBUILD"):
    subprocess.run(["c++", "-O2", "-std=c++17", "-o", "tools/router/fastroute", "tools/router/fastroute.cpp"], check=True)
subprocess.run(["tools/router/fastroute", "routing/inputs/PART.fr.txt", "routing/inputs/PART.fr.out", "--time", tlimit, "--neck", neck], check=True)
cmd = [sys.executable, "-I", "tools/router/post.py", "--part", ",".join(want)]
if keep: cmd += ["--add", ",".join(keep)]
subprocess.run(cmd, check=True)