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-motherboardIn 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/prep.py
"""Turn the dumped routing problem into the flat text file the native router reads.
python3 -I tools/router/prep.py [--layers top,bottom]
Reads routing/inputs/ALL.input.json (core's routing problem, from ROUTE_DUMP=1 tsci build)
dist/index/circuit.json (net names)
circuit/power-copper.json (top power pours: other nets should stay out of them)
data/planes.json (where a via reaches each power plane)
Writes routing/inputs/ALL.fr.txt
"""
import json, sys
args = dict(zip(sys.argv[1::2], sys.argv[2::2]))
RL = args.get("--layers", "top,bottom").split(",")
srj = json.load(open("routing/inputs/ALL.input.json"))
cj = json.load(open("dist/index/circuit.json"))
pours = json.load(open("circuit/power-copper.json"))["pours"]
planes = json.load(open("data/planes.json"))
ALL = ["top", "inner1", "inner2", "bottom"][: srj["layerCount"]] if srj["layerCount"] == 4 else None
assert ALL, "4-layer board expected"
name_of = {e["source_net_id"]: e["name"] for e in cj if e["type"] == "source_net"}
# A few connections are single <trace> elements with their own limits (the hub crystal: no vias, <= 10 mm).
# They belong to a net that also has its own connection; route them as part of that net and keep the limits.
all_conns = srj["connections"]
alias = {c["name"]: (c.get("netConnectionName") or c["name"]) for c in all_conns}
conns = [c for c in all_conns if alias[c["name"]] == c["name"]]
cidx = {c["name"]: i for i, c in enumerate(conns)}
for c in all_conns: cidx.setdefault(c["name"], cidx.get(alias[c["name"]], -1))
novia = set(); maxlen = {}
for c in all_conns:
i = cidx[c["name"]]
if i < 0: continue
if c.get("maxViaCount") == 0: novia.add(i)
if c.get("maxLength"): maxlen[i] = min(maxlen.get(i, 1e9), c["maxLength"])
pair_of = {}
for k, b in enumerate(srj.get("buses") or []):
for cn in b["connectionNames"]:
if cn in cidx: pair_of[cidx[cn]] = k
out = []
ol = srj["outline"]
xs = [p["x"] for p in ol]; ys = [p["y"] for p in ol]
out.append(f"G {min(xs)} {min(ys)} {max(xs)} {max(ys)} 0.05")
out.append(f"RULE {srj['minTraceToPadEdgeClearance']} {srj['minViaPadDiameter']} {srj['minViaHoleDiameter']} {srj['minBoardEdgeClearance']} {srj['minTraceToHoleEdgeClearance']}")
out.append("L " + " ".join(ALL))
out.append("RL " + " ".join(str(ALL.index(l)) for l in RL))
net_by_name = {}
for i, c in enumerate(conns):
nm = name_of.get(c["name"], c["name"]).replace(" ", "_")
net_by_name[nm] = i
pl = planes.get(nm)
out.append(f"N {i} {nm} {c.get('width') or c.get('nominalTraceWidth') or 0.1} {1 if pl else 0} {ALL.index(pl['layer']) if pl else -1} {pair_of.get(i, -1)} {1 if i in novia else 0} {maxlen.get(i, 0)}")
def mask(layers): return sum(1 << ALL.index(l) for l in layers if l in ALL)
# Core's routing problem ignores the rotation of pill-shaped plated holes (USB-C shell slots turned 90 deg
# come out as 1.2 x 2.0 instead of 2.0 x 1.2), so their size is taken from the circuit JSON instead.
import math
plated = {e["pcb_plated_hole_id"]: e for e in cj if e["type"] == "pcb_plated_hole"}
def plated_size(e):
w = e.get("outer_width", e.get("outer_diameter")); h = e.get("outer_height", e.get("outer_diameter"))
r = math.radians(e.get("ccw_rotation") or 0); c, sn = abs(math.cos(r)), abs(math.sin(r))
return w * c + h * sn, w * sn + h * c
pad_of_port = {}
npad = 0
# Parts whose centre pad gets ground vias inside it. Only the CH338F hub: its centre pad is its one ground pin and
# its pin ring leaves no room for a track or a via between pad and pins. Every other centre pad has a way out.
THERMAL_VIA_PARTS = {"UHUB"}
_hints = {e["source_port_id"]: e for e in cj if e["type"] == "source_port"}
_names = {e["source_component_id"]: e["name"] for e in cj if e["type"] == "source_component"}
thermal_ports = {e["pcb_port_id"] for e in cj if e["type"] == "pcb_port" and "thermalpad" in (_hints.get(e.get("source_port_id"), {}).get("port_hints") or [])
and _names.get(_hints[e["source_port_id"]].get("source_component_id")) in THERMAL_VIA_PARTS}
thermal = []
for o in srj["obstacles"]:
if o.get("isCopperPour"): continue
net = next((cidx[c] for c in o["connectedTo"] if cidx.get(c, -1) >= 0), -1)
md = o.get("circuitJsonMetadata") or {}
circle = o.get("shape") == "circle"
if md.get("pcb_smtpad_id") or md.get("pcb_plated_hole_id"): kind = 0
elif md.get("pcb_via_id") or (circle and net >= 0 and len(o["layers"]) == 4): kind = 2
elif net < 0 and len(o["layers"]) == 4: kind = 1 # unplated hole / keep-out
else: kind = 0
w, h = o["width"], o["height"]
if md.get("pcb_plated_hole_id") in plated: w, h = plated_size(plated[md["pcb_plated_hole_id"]])
out.append(f"PAD {net} {mask(o['layers'])} {o['center']['x']} {o['center']['y']} {w} {h} {kind} {1 if circle else 0}")
if md.get("pcb_port_id"): pad_of_port[md["pcb_port_id"]] = npad
# centre (thermal) pad of a plane net: the router puts vias inside it
if md.get("pcb_port_id") in thermal_ports and net >= 0 and planes.get(name_of.get(conns[net]["name"], conns[net]["name"]).replace(" ", "_")): thermal.append(npad)
npad += 1
out += [f"TPAD {k}" for k in thermal]
# USB pair nets: list the host pin first (SoC, else hub). The router grows a pair net outward from its first
# pin, so both lines of a pair get the same shape of tree and their signal paths come out close in length.
_src = {e["source_component_id"]: e["name"] for e in cj if e["type"] == "source_component"}
_sp = {e["source_port_id"]: e for e in cj if e["type"] == "source_port"}
_comp = {e["pcb_port_id"]: _src.get(_sp[e["source_port_id"]].get("source_component_id"), "") for e in cj if e["type"] == "pcb_port"}
def host_rank(p): return {"UMPU": 0, "UHUB": 1}.get(_comp.get(p.get("pcb_port_id"), ""), 2)
missing = 0; seen_pin = set()
for c in all_conns:
i = cidx[c["name"]]
if i < 0: continue
for p in (sorted(c["pointsToConnect"], key=host_rank) if i in pair_of else c["pointsToConnect"]):
if (i, p.get("pcb_port_id")) in seen_pin: continue
seen_pin.add((i, p.get("pcb_port_id")))
pad = pad_of_port.get(p.get("pcb_port_id"), -1)
if pad < 0: missing += 1
out.append(f"PIN {i} {p['x']} {p['y']} {mask([p['layer']])} {pad}")
# USB pair jobs: where each pair's long run starts (at the host pins) and ends (at the first part that has
# pins of both lines: the ESD chip, or the hub for the upstream pair), the direction it leaves and arrives
# in, and which line is on the left. The router lays the run as one wide track and splits it into two lines.
_pos = {e["pcb_port_id"]: (e["x"], e["y"]) for e in cj if e["type"] == "pcb_port"}
_cpins = {}
for pid, cname in _comp.items(): _cpins.setdefault(cname, []).append(_pos[pid])
_centre = {c: (sum(x for x, _ in v) / len(v), sum(y for _, y in v) / len(v)) for c, v in _cpins.items()}
_padwh = {}
for o in srj["obstacles"]:
md = o.get("circuitJsonMetadata") or {}
if md.get("pcb_port_id"): _padwh[md["pcb_port_id"]] = (o["width"], o["height"])
def _out(pid): # outward direction of a pin from its part, snapped to an axis
cx, cy = _centre[_comp[pid]]; x, y = _pos[pid]; dx, dy = x - cx, y - cy
return (1 if dx > 0 else -1, 0) if abs(dx) >= abs(dy) else (0, 1 if dy > 0 else -1)
def _halflen(pid, u): w, h = _padwh.get(pid, (0.3, 0.3)); return (abs(u[0]) * w + abs(u[1]) * h) / 2
def _snap(v): return round(round(v / 0.05) * 0.05, 4)
def _left(u): return (-u[1], u[0])
_by_pair = {}; _jobs = []
for i, k in pair_of.items(): _by_pair.setdefault(k, []).append(i)
for k, (na, nb) in sorted(_by_pair.items()):
nP, nN = (na, nb) if name_of.get(conns[na]["name"], "").endswith("_DP") else (nb, na)
pins = {n: [p["pcb_port_id"] for c in all_conns if cidx[c["name"]] == n for p in c["pointsToConnect"]] for n in (nP, nN)}
rank = lambda pid: {"UMPU": 0, "UHUB": 1}.get(_comp[pid], 2)
hP = min(pins[nP], key=rank); hN = min(pins[nN], key=rank); host = _comp[hP]
if _comp[hN] != host or _out(hP) != _out(hN): continue
u0 = _out(hP); mx, my = (_pos[hP][0] + _pos[hN][0]) / 2, (_pos[hP][1] + _pos[hN][1]) / 2
d0 = _halflen(hP, u0) + 0.35
S = (_snap(mx + u0[0] * d0), _snap(my + u0[1] * d0))
p_left = (_pos[hP][0] - _pos[hN][0]) * _left(u0)[0] + (_pos[hP][1] - _pos[hN][1]) * _left(u0)[1] > 0
# far part: nearest other part with pins of both lines
cands = []
for a in pins[nP]:
for b in pins[nN]:
if _comp[a] != _comp[b] or _comp[a] == host or _out(a) != _out(b): continue
od = _out(a); arrive = (-od[0], -od[1])
ok = ((_pos[a][0] - _pos[b][0]) * _left(arrive)[0] + (_pos[a][1] - _pos[b][1]) * _left(arrive)[1] > 0) == p_left
sep = abs(_pos[a][0] - _pos[b][0]) + abs(_pos[a][1] - _pos[b][1])
m = ((_pos[a][0] + _pos[b][0]) / 2, (_pos[a][1] + _pos[b][1]) / 2)
dt = _halflen(a, od) + (0.35 if sep < 0.7 else 0.75) # stop short when another pin sits between the two
T = (_snap(m[0] + od[0] * dt), _snap(m[1] + od[1] * dt))
cands.append((abs(_centre[_comp[a]][0] - S[0]) + abs(_centre[_comp[a]][1] - S[1]), not ok, abs(T[0] - S[0]) + abs(T[1] - S[1]), _comp[a], T, arrive, ok))
if not cands: continue
near = min(c[0] for c in cands)
best = min((c for c in cands if c[0] <= near + 1e-6), key=lambda c: (c[1], c[2]))
_, _, _, far, T, arrive, ok = best
# jobs are tried in this order: SoC pairs first, then the hub's pairs in the order their pins sit along the hub
_jobs.append(((0 if host == "UMPU" else 1, S[1] * abs(u0[0]) + S[0] * abs(u0[1])), f"PAIRJOB {k} {nP} {nN} {S[0]} {S[1]} {u0[0]} {u0[1]} {T[0]} {T[1]} {arrive[0]} {arrive[1]} {1 if p_left else 0} {1 if ok else 0} {0 if host == 'UMPU' else 1}"))
print(f" pair {name_of.get(conns[nP]['name'])[:-3]}: {host} {S} heading {u0} -> {far} {T} arriving {arrive}; D+ on the {'left' if p_left else 'right'}; order {'matches' if ok else 'IS CROSSED at the far end'}")
out += [line for _, line in sorted(_jobs)]
for p in pours:
if p["net"] == "GND" or p["net"] not in net_by_name: continue
out.append(f"POUR {net_by_name[p['net']]} 0 {len(p['outline'])} " + " ".join(f"{q['x']} {q['y']}" for q in p["outline"]))
for nm, pl in planes.items():
if nm in net_by_name:
out.append(f"PLANE {net_by_name[nm]} {len(pl['outline'])} " + " ".join(f"{x} {y}" for x, y in pl["outline"]))
out.append(f"OUT {len(ol)} " + " ".join(f"{p['x']} {p['y']}" for p in ol))
open("routing/inputs/ALL.fr.txt", "w").write("\n".join(out) + "\n")
print(f"nets {len(conns)}, pads {npad}, pins {len(seen_pin)} ({missing} without a pad), no-via nets {len(novia)}, routing layers {RL}")