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/audit.py
"""Quality report for routing/ALL.routed.json: python3 -I tools/router/audit.py
Power-net widths (how much necked to 0.1 mm), USB pair lengths/skew/vias, length-limited nets, copper per layer."""
import json, math, collections
R = json.load(open("routing/ALL.routed.json"))
nets = {}; pair = {}; maxlen = {}; novia = set(); width = {}
for l in open("routing/inputs/ALL.fr.txt"):
t = l.split()
if t[0] == "N":
nets[int(t[1])] = t[2]; width[t[2]] = float(t[3])
if int(t[6]) >= 0: pair.setdefault(int(t[6]), []).append(t[2])
if int(t[7]): novia.add(t[2])
if float(t[8]): maxlen[t[2]] = float(t[8])
# pads per net: a thin stub that lies inside the net's own pad is not a neck (the pad copper is around it)
padsof = collections.defaultdict(list)
for l in open("routing/inputs/ALL.fr.txt"):
t = l.split()
if t[0] == "PAD" and int(t[1]) >= 0: padsof[nets[int(t[1])]].append((float(t[3]), float(t[4]), float(t[5]) / 2 + 0.06, float(t[6]) / 2 + 0.06))
def in_own_pad(net, x, y): return any(abs(x - px) <= hw and abs(y - py) <= hh for px, py, hw, hh in padsof[net])
bynet = collections.defaultdict(lambda: {"len": collections.Counter(), "layer": collections.Counter(), "vias": 0, "inpad": 0.0})
for r in R:
b = bynet[r["net"]]; pts = r["route"]
for a, c in zip(pts, pts[1:]):
if a["route_type"] == "wire" and c["route_type"] == "wire" and a["layer"] == c["layer"]:
d = math.hypot(a["x"] - c["x"], a["y"] - c["y"]); b["layer"][c["layer"]] += d
if c["width"] <= 0.1001 and in_own_pad(r["net"], (a["x"] + c["x"]) / 2, (a["y"] + c["y"]) / 2): b["inpad"] += d
else: b["len"][c["width"]] += d
b["vias"] += sum(1 for p in pts if p["route_type"] == "via")
tot = collections.Counter()
for b in bynet.values(): tot.update(b["layer"])
print("copper:", {k: f"{v:.0f} mm" for k, v in tot.items()}, " vias:", sum(b["vias"] for b in bynet.values()), " routes:", len(R))
print("\nwide nets, mm of trace at each width (stubs inside the net's own pads left out):")
for n, w in sorted(width.items()):
if w > 0.1001 and n in bynet:
b = bynet[n]
print(f" {n:12s} target {w}: " + " ".join(f"{k} mm: {v:6.1f}" for k, v in sorted(b["len"].items(), reverse=True)) + f" vias {b['vias']}")
# USB pairs: length of the actual signal path, host pin (hub or SoC) -> connector pin, per line
import heapq
cj = json.load(open("dist/index/circuit.json"))
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_at = {}
for e in cj:
if e["type"] == "pcb_port":
q = sp[e["source_port_id"]]; comp_at[(round(e["x"], 3), round(e["y"], 3))] = src.get(q.get("source_component_id"), "?")
def path_lengths(net):
"""shortest copper path from the host pin to every connector pin: [(length, vias, bottom mm)]"""
segs = []; ends = []; adj = collections.defaultdict(list)
def node(p, layer): return (round(p["x"], 3), round(p["y"], 3), layer)
for r in R:
if r["net"] != net: continue
pts = r["route"]; lay = None
for k, p in enumerate(pts):
if p["route_type"] == "wire":
if lay is not None and k and pts[k - 1]["route_type"] == "wire": segs.append((node(pts[k - 1], lay), node(p, p["layer"])))
lay = p["layer"]
else:
a, c = node(p, p["from_layer"]), node(p, p["to_layer"]); adj[a].append((c, 0, 1, 0)); adj[c].append((a, 0, 1, 0))
wires = [p for p in pts if p["route_type"] == "wire"]
ends += [node(wires[0], wires[0]["layer"]), node(wires[-1], wires[-1]["layer"])]
for a, c in segs: # split segments where another route of the net ends on them
cuts = [a, c]
for e in ends:
if e[2] != a[2] or e in (a, c): continue
vx, vy = c[0] - a[0], c[1] - a[1]; L2 = vx * vx + vy * vy
if L2 == 0: continue
t = ((e[0] - a[0]) * vx + (e[1] - a[1]) * vy) / L2
if 0 < t < 1 and abs((e[0] - a[0]) * vy - (e[1] - a[1]) * vx) / math.sqrt(L2) < 2e-3: cuts.append(e)
cuts.sort(key=lambda q: (q[0] - a[0]) ** 2 + (q[1] - a[1]) ** 2)
for u, v in zip(cuts, cuts[1:]):
d = math.hypot(u[0] - v[0], u[1] - v[1]); bot = d if a[2] == "bottom" else 0
adj[u].append((v, d, 0, bot)); adj[v].append((u, d, 0, bot))
soc = [n for n in adj if comp_at.get(n[:2]) == "UMPU"]; hub = [n for n in adj if comp_at.get(n[:2]) == "UHUB"]
hosts = soc or hub # SoC -> hub for the upstream pair, hub -> connector for the rest
conns = [n for n in adj if str(comp_at.get(n[:2], "")).startswith("J")] or (hub if soc else [])
if not hosts: return []
dist = {hosts[0]: (0, 0, 0)}; pq = [(0, 0, 0, hosts[0])]
while pq:
d, v, b, u = heapq.heappop(pq)
if dist.get(u, (1e9,))[0] < d: continue
for w, dd, dv, db in adj[u]:
if d + dd < dist.get(w, (1e9,))[0] - 1e-9: dist[w] = (d + dd, v + dv, b + db); heapq.heappush(pq, (d + dd, v + dv, b + db, w))
return sorted(dist[c] for c in conns if c in dist)
print("\nUSB pairs, host pin -> nearest far-end pin (signal path):")
for k, (a, c) in sorted(pair.items()):
pa, pc = path_lengths(a), path_lengths(c)
if not pa or not pc: print(f" {a}/{c}: path not found"); continue
(la, va, ba), (lc, vc, bc) = pa[0], pc[0]
print(f" {a:8s}/{c:8s} {la:6.2f} / {lc:6.2f} mm skew {abs(la - lc):5.2f} mm vias {va}/{vc} on bottom {ba:.1f}/{bc:.1f} mm")
# how much of each pair really runs side by side (the impedance target only holds there)
def _segs(net):
o = []
for r in R:
if r["net"] != net: continue
p = r["route"]
for a, c in zip(p, p[1:]):
if a["route_type"] == "wire" and c["route_type"] == "wire" and a["layer"] == c["layer"] and math.hypot(a["x"] - c["x"], a["y"] - c["y"]) > 1e-9:
o.append((a["x"], a["y"], c["x"], c["y"], a["layer"]))
return o
def _d(px, py, q):
vx, vy = q[2] - q[0], q[3] - q[1]; L2 = vx * vx + vy * vy; t = max(0, min(1, ((px - q[0]) * vx + (py - q[1]) * vy) / L2))
return math.hypot(px - (q[0] + t * vx), py - (q[1] + t * vy))
print("\nUSB pair coupling, share of the D- line's length by distance to D+ (centre to centre):")
for k, (a, c) in sorted(pair.items()):
A, B = _segs(a), _segs(c); tot = near = mid = 0.0
pitch = math.ceil((width[a] + 0.112) / 0.05 - 1e-9) * 0.05
for q in A:
L = math.hypot(q[2] - q[0], q[3] - q[1]); n = max(1, int(L / 0.05))
for i in range(n):
t = (i + 0.5) / n; d = min((_d(q[0] + (q[2] - q[0]) * t, q[1] + (q[3] - q[1]) * t, b) for b in B if b[4] == q[4]), default=99)
tot += L / n; near += L / n if d <= pitch + 0.012 else 0; mid += L / n if pitch + 0.012 < d <= 0.6 else 0
print(f" {a[:-3]:5s} at {pitch:.2f} mm: {100 * near / tot:3.0f} % up to 0.6 mm: {100 * mid / tot:3.0f} % farther: {100 * (tot - near - mid) / tot:3.0f} %")
print("\nlength-limited nets:")
for n, m in maxlen.items():
print(f" {n}: {sum(bynet[n]['len'].values()) + bynet[n]['inpad']:.1f} mm of {m} allowed, vias {bynet[n]['vias']}{' (none allowed)' if n in novia else ''}")