rushabhcodes/usb-c-e-paper-display

USB-C powered RP2354B controller board with protected power regulation, EPD display interface and charge-pump rails, crystal timing, user/boot switches, status LEDs, and SWD test points.

Version
1.4.1
License
unset
Stars
0

Use with the tscircuit CLI

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

tsci clone rushabhcodes/usb-c-e-paper-display  # download the package files into ./usb-c-e-paper-display
tsci add rushabhcodes/usb-c-e-paper-display    # add it to your project as @tsci/rushabhcodes.usb-c-e-paper-display

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.

scripts/check-fabrication-connectivity.py

"""Read-only independent connectivity check of exported Gerber/Excellon files.

Copper is reconstructed from Gerber primitives, not tscircuit's short checker.
Circles use 256-sided approximation; net names come from source connectivity.
"""
import collections
import json
import math
import warnings
from pathlib import Path

from gerbonara import ExcellonFile, GerberFile
from gerbonara import graphic_primitives as gp
from gerbonara.utils import MM
from shapely import STRtree
from shapely.geometry import LineString, Point, Polygon
from shapely.ops import unary_union

import argparse
import hashlib
import tempfile
import zipfile

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('archive', nargs='?', default='manufacturing/JLCPCB-Gerbers-RevD.zip')
parser.add_argument('--circuit', default='manufacturing/design.circuit.json')
parser.add_argument('--report', default='manufacturing/checks/gerber-connectivity.json')
args = parser.parse_args()
archive = Path(args.archive)
work = tempfile.TemporaryDirectory(prefix='epaper-copper-')
GERBERS = Path(work.name)
with zipfile.ZipFile(archive) as z:
    for name in ['F_Cu.gbr', 'In1_Cu.gbr', 'In2_Cu.gbr', 'B_Cu.gbr',
                 'F_Mask.gbr', 'drill-L1-L4.drl', 'drill_npth.drl']:
        (GERBERS / name).write_bytes(z.read(name))
data = json.loads(Path(args.circuit).read_text())

def geom(p):
    if isinstance(p, gp.Circle):
        return Point(p.x, p.y).buffer(p.r, quad_segs=64)
    if isinstance(p, gp.Line):
        return LineString([(p.x1, p.y1), (p.x2, p.y2)]).buffer(p.width / 2, quad_segs=64)
    if isinstance(p, gp.Rectangle):
        return Polygon(p.to_arc_poly().outline)
    if isinstance(p, gp.ArcPoly):
        return Polygon(p.approximate_arcs(max_error=0.00001).outline)
    raise ValueError(type(p))

def copper(path):
    f = GerberFile.open(path)
    result = Polygon()
    previous = True
    batch = []
    for o in f.objects:
        for p in o.to_primitives(unit=MM):
            if p.polarity_dark != previous and batch:
                part = unary_union(batch)
                result = result.union(part) if previous else result.difference(part)
                batch = []
            previous = p.polarity_dark
            batch.append(geom(p))
    if batch:
        part = unary_union(batch)
        result = result.union(part) if previous else result.difference(part)
    assert result.is_valid, path
    return f, result

layers = ['top', 'inner1', 'inner2', 'bottom']
names = ['F_Cu.gbr', 'In1_Cu.gbr', 'In2_Cu.gbr', 'B_Cu.gbr']
source_board = next(e for e in data if e['type'] == 'pcb_board')
board = Polygon([(v['x'], v['y']) for v in source_board['outline']])
polys, trees, layer_info = {}, {}, {}
parent = {}
def find(k):
    parent.setdefault(k, k)
    if parent[k] != k:
        parent[k] = find(parent[k])
    return parent[k]
def join(a, b):
    parent[find(a)] = find(b)

for layer, name in zip(layers, names):
    f, shape = copper(GERBERS / name)
    polys[layer] = list(shape.geoms) if shape.geom_type == 'MultiPolygon' else [shape]
    trees[layer] = STRtree(polys[layer])
    for i in range(len(polys[layer])):
        find((layer, i))
    # Distinct islands include disconnected pieces of the same electrical net.
    minimum_gap = min((p.distance(q) for i, p in enumerate(polys[layer])
                       for q in polys[layer][i + 1:]), default=None)
    outside = shape.difference(board).area
    widths = [p.width for o in f.objects for p in o.to_primitives(unit=MM)
              if isinstance(p, gp.Line)]
    layer_info[layer] = {'copper_islands': len(polys[layer]),
        'minimum_disjoint_island_gap_mm': minimum_gap,
        'minimum_copper_edge_clearance_mm': shape.distance(board.boundary),
        'outside_outline_area_mm2': outside,
        'minimum_drawn_line_width_mm': min(widths, default=None)}

def islands_at(x, y, layer, tolerance=0.00001):
    return [(layer, int(i)) for i in trees[layer].query(Point(x, y).buffer(tolerance), predicate='intersects')]

with warnings.catch_warnings(record=True) as drill_warnings:
    pth = ExcellonFile.open(GERBERS / 'drill-L1-L4.drl')
    npth = ExcellonFile.open(GERBERS / 'drill_npth.drl')
drill_geoms = []
unconnected_drills = []
for o in pth.objects:
    prims = list(o.to_primitives(unit=MM))
    g = unary_union([geom(p) for p in prims])
    c = g.centroid
    hit = [k for layer in layers for k in islands_at(c.x, c.y, layer)]
    for k in hit[1:]:
        join(hit[0], k)
    if len(hit) < 2:
        unconnected_drills.append([c.x, c.y])
    drill_geoms.append(g)

drill_gap = min(a.distance(b) for i, a in enumerate(drill_geoms) for b in drill_geoms[i + 1:])
drill_edge = min(g.distance(board.boundary) for g in drill_geoms)
# Excellon G85 slots are preceded by a drill hit at the slot start. This is
# normal overlap within one routed slot, not two colliding holes.
drilled_union = unary_union(drill_geoms)
distinct_holes = list(drilled_union.geoms)
distinct_drill_gap = min(a.distance(b) for i, a in enumerate(distinct_holes) for b in distinct_holes[i + 1:])
for layer in layers:
    candidates = [(p.distance(q), i, j) for i, p in enumerate(polys[layer])
                  for j, q in enumerate(polys[layer][i + 1:], i + 1)
                  if find((layer, i)) != find((layer, j))]
    gap, i, j = min(candidates)
    layer_info[layer]['minimum_separate_electrical_cluster_gap_mm'] = gap
    layer_info[layer]['closest_separate_cluster_centres_mm'] = [list(polys[layer][k].centroid.coords)[0] for k in (i, j)]
_, mask = copper(GERBERS / 'F_Mask.gbr')
mask_islands = list(mask.geoms)
mask_gap = min(a.distance(b) for i, a in enumerate(mask_islands) for b in mask_islands[i + 1:])
npth_shapes = [geom(p) for o in npth.objects for p in o.to_primitives(unit=MM)]
npth_copper_gap = min(p.distance(h) for ps in polys.values() for p in ps for h in npth_shapes)

# Expected net membership is computed from explicit source traces, with the
# physical top/bottom ports of each declared via treated as the same terminal.
source_parent = {}
def sf(k):
    source_parent.setdefault(k, k)
    if source_parent[k] != k:
        source_parent[k] = sf(source_parent[k])
    return source_parent[k]
def sj(a, b):
    source_parent[sf(a)] = sf(b)
ports = {e['source_port_id']: e for e in data if e['type'] == 'source_port'}
for e in data:
    if e['type'] == 'source_trace':
        ids = e.get('connected_source_port_ids', []) + e.get('connected_source_net_ids', [])
        for k in ids[1:]:
            sj(ids[0], k)
vias = {e['source_manually_placed_via_id'] for e in data if e['type'] == 'source_manually_placed_via'}
for via in vias:
    vp = [p['source_port_id'] for p in ports.values() if p.get('source_component_id') == via]
    for k in vp[1:]:
        sj(vp[0], k)
net_labels = collections.defaultdict(set)
for e in data:
    if e['type'] == 'source_net':
        net_labels[sf(e['source_net_id'])].add(e['name'])
components = {e['source_component_id']: e for e in data if e['type'] == 'source_component'}
pins_by_cluster, clusters_by_net = collections.defaultdict(list), collections.defaultdict(set)
missing_pins = []
unassigned = []
for e in data:
    if e['type'] != 'pcb_port' or e.get('source_port_id') not in ports:
        continue
    p = ports[e['source_port_id']]
    if p.get('source_component_id') not in components:
        continue
    labels = net_labels.get(sf(p['source_port_id']), set())
    if not labels:
        ref = components[p['source_component_id']]['name'] + '.' + p['name']
        hit = [k for layer in e['layers'] for k in islands_at(e['x'], e['y'], layer)]
        unassigned.extend((ref, find(k)) for k in hit)
        continue
    assert len(labels) == 1, labels
    label = next(iter(labels))
    ref = components[p['source_component_id']]['name'] + '.' + p['name']
    hit = [k for layer in e['layers'] for k in islands_at(e['x'], e['y'], layer)]
    if not hit:
        missing_pins.append(ref)
    for k in hit:
        cluster = find(k)
        pins_by_cluster[cluster].append((label, ref))
        clusters_by_net[label].add(cluster)
shorts = [v for v in pins_by_cluster.values() if len({n for n, _ in v}) > 1]
opens = {n: len(v) for n, v in clusters_by_net.items() if len(v) > 1}
unexpected = [(ref, sorted({n for n, _ in pins_by_cluster[k]}))
              for ref, k in unassigned if k in pins_by_cluster]
report = {'method': 'Independent Gerbonara + Shapely reconstruction of released Gerber copper, joined only at plated drills',
    'circle_approximation_sides': 256, 'layers': layer_info,
    'plated_drill_features': len(pth.objects), 'nonplated_drills': len(npth.objects),
    'minimum_plated_drill_edge_to_edge_mm': drill_gap,
    'distinct_plated_hole_count': len(distinct_holes),
    'minimum_distinct_plated_hole_edge_to_edge_mm': distinct_drill_gap,
    'minimum_plated_drill_to_outline_mm': drill_edge,
    'minimum_front_soldermask_web_mm': mask_gap,
    'minimum_npth_to_copper_mm': npth_copper_gap,
    'drills_without_copper_on_multiple_layers': unconnected_drills,
    'nets_checked': len(clusters_by_net), 'shorts': shorts, 'opens': opens, 'missing_connected_pins': missing_pins,
    'unassigned_pins_unexpectedly_touching_named_nets': unexpected,
    'parser_notes': [str(w.message) for w in drill_warnings]}
report['result'] = 'PASS' if not (shorts or opens or missing_pins or unexpected or unconnected_drills) and len(clusters_by_net) == sum(e['type'] == 'source_net' for e in data) else 'FAIL'
report['archive_sha256'] = hashlib.sha256(archive.read_bytes()).hexdigest()
report['circuit_canonical_sha256'] = hashlib.sha256(json.dumps(data, separators=(',', ':')).encode()).hexdigest()
target = Path(args.report)
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(json.dumps(report, indent=2) + '\n')
print(json.dumps({k: report[k] for k in ['result', 'nets_checked', 'shorts', 'opens', 'missing_connected_pins', 'unassigned_pins_unexpectedly_touching_named_nets']}, indent=2))
assert report['result'] == 'PASS', 'Actual Gerber copper differs from intended connectivity'