MustafaMulla29/bluetooth-connected-pedometer
It defines a PCB footprint and schematic symbol for a row of solder pads used as wire connection points, featuring customizable spacing and label annotations.
- Version
- 0.3.0
- License
- unset
- Stars
- 0
Use with the tscircuit CLI
tsci is the tscircuit CLI. Install it with npm install -g tscircuit.
tsci clone MustafaMulla29/bluetooth-connected-pedometer # download the package files into ./bluetooth-connected-pedometer
tsci add MustafaMulla29/bluetooth-connected-pedometer # add it to your project as @tsci/MustafaMulla29.bluetooth-connected-pedometerIn 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.py
#!/usr/bin/env python3
"""Independent geometric checks of copper, drill and physical connectivity.
Requires shapely. Geometry is in mm, straight-segment/round copper primitives.
This deliberately supplements, rather than suppresses, tscircuit's checks.
"""
import collections, hashlib, json, math, re, sys
from pathlib import Path
from shapely.geometry import Point, LineString, Polygon, box
from shapely.affinity import rotate
from shapely.ops import unary_union
from shapely.strtree import STRtree
root=Path(__file__).resolve().parents[1]
path=root/'dist/index/circuit.json'
items=json.loads(path.read_text())
parent={}
def find(x):
parent.setdefault(x,x)
if parent[x]!=x: parent[x]=find(parent[x])
return parent[x]
def join(a,b):parent[find(a)]=find(b)
for o in items:
if o['type']=='source_trace':
ids=[o['source_trace_id']]+o.get('connected_source_port_ids',[])+o.get('connected_source_net_ids',[])
if o.get('subcircuit_connectivity_map_key'):ids.append(o['subcircuit_connectivity_map_key'])
for x in ids[1:]:join(ids[0],x)
nets={find(o['source_net_id']):o['name'] for o in items if o['type']=='source_net'}
ports={o['pcb_port_id']:o for o in items if o['type']=='pcb_port'}
traces={o['pcb_trace_id']:o for o in items if o['type']=='pcb_trace'}
def net(o):
for key in ['source_net_id','source_trace_id','subcircuit_connectivity_map_key']:
if o.get(key):return find(o[key])
if o.get('pcb_port_id'):return find(ports[o['pcb_port_id']]['source_port_id'])
if o.get('pcb_trace_id') in traces and o is not traces[o['pcb_trace_id']]:return net(traces[o['pcb_trace_id']])
name=o.get('connection_name','')
m=re.match(r'(source_net_\d+)',name)
if m:return find(m[1])
route=o.get('route',[])
for p in route:
for key in ['start_pcb_port_id','end_pcb_port_id']:
if p.get(key) in ports:return find(ports[p[key]]['source_port_id'])
return 'unassigned:'+str(o.get('pcb_trace_id',o.get('pcb_via_id','')))
board=next(o for o in items if o['type']=='pcb_board')
layer_count=board['num_layers']
assert layer_count in (2,4), 'Fabrication audit supports two- and four-layer boards'
layers=['top']+[f'inner{i}' for i in range(1,layer_count-1)]+['bottom']
shapes=[]; drills=[]; violations=[]
for o in items:
if o['type'] in ('pcb_smtpad','pcb_copper_pour'):
assert o['layer'] in layers, f"Copper on nonexistent board layer: {o['type']} {o['layer']}"
elif o['type']=='pcb_trace':
for point in o['route']:
if point['route_type']=='wire':
assert point['layer'] in layers, f"Trace on nonexistent board layer: {point['layer']}"
def add(g,o,kind,layer,label):shapes.append((g,net(o),kind,layer,label))
def xy(p):return (p['x'],p['y'])
for o in items:
typ=o['type']
if typ=='pcb_smtpad':
if o['shape']=='circle':g=Point(o['x'],o['y']).buffer(o['radius'],resolution=32)
elif o['shape'] in ['rect','rotated_rect']:
g=box(o['x']-o['width']/2,o['y']-o['height']/2,o['x']+o['width']/2,o['y']+o['height']/2)
if o.get('ccw_rotation'):g=rotate(g,o['ccw_rotation'],origin=(o['x'],o['y']))
else:raise ValueError('Unsupported pad shape '+o['shape'])
add(g,o,'pad',o['layer'],o['pcb_smtpad_id'])
elif typ=='pcb_trace':
previous=None
for p in o['route']:
if p['route_type']=='wire':
if p['width']<(.1 if layer_count==2 else .09)-1e-6:violations.append({'kind':'width','trace':o['pcb_trace_id'],'width':p['width']})
if previous and previous.get('layer')==p['layer']:
g=LineString([xy(previous),xy(p)]).buffer(max(previous['width'],p['width'])/2,resolution=16)
if not g.is_empty:add(g,o,'track',p['layer'],o['pcb_trace_id'])
previous=p
elif p['route_type'] in ('via','through_pad'):previous=None
else:raise ValueError('Unsupported route primitive '+p['route_type'])
elif typ in ('pcb_via','pcb_plated_hole'):
label=o.get('pcb_via_id',o.get('pcb_plated_hole_id'))
# Native pin escapes can use a rectangular copper land around a round drill.
if typ=='pcb_plated_hole' and o.get('shape')=='circular_hole_with_rect_pad':
w,h=o['rect_pad_width'],o['rect_pad_height']
g=box(o['x']-w/2,o['y']-h/2,o['x']+w/2,o['y']+h/2)
if o.get('rect_border_radius'):raise ValueError('Rounded plated lands not yet supported')
angle=o.get('rect_ccw_rotation',0)
if angle:g=rotate(g,angle,origin=(o['x'],o['y']))
drill_center=Point(o['x']+o.get('hole_offset_x',0),o['y']+o.get('hole_offset_y',0))
if angle:drill_center=rotate(drill_center,angle,origin=(o['x'],o['y']))
annulus=drill_center.distance(g.boundary)-o['hole_diameter']/2
elif typ=='pcb_via' or o.get('shape')=='circle':
g=Point(o['x'],o['y']).buffer(o['outer_diameter']/2,resolution=32)
drill_center=Point(o['x'],o['y'])
annulus=(o['outer_diameter']-o['hole_diameter'])/2
else:raise ValueError('Unsupported plated hole shape '+str(o.get('shape')))
for layer in o['layers']:add(g,o,'via',layer,label)
drills.append((drill_center.buffer(o['hole_diameter']/2,resolution=32),net(o),label))
if o['hole_diameter']<.30-1e-6 or annulus<.075-1e-6:
violations.append({'kind':'via_dimensions','via':label})
# Plated holes omit explicit endpoints; their layer list defines the span.
from_layer=o.get('from_layer','top' if typ=='pcb_plated_hole' else None)
to_layer=o.get('to_layer','bottom' if typ=='pcb_plated_hole' else None)
if set(o['layers'])!=set(layers) or {from_layer,to_layer}!={'top','bottom'}:
violations.append({'kind':'non_through_via','via':label,
'layers':o['layers'],'from_layer':from_layer,'to_layer':to_layer})
elif typ=='pcb_copper_pour':
b=o['brep_shape'];g=Polygon([xy(p) for p in b['outer_ring']['vertices']],[[xy(p) for p in ring['vertices']] for ring in b.get('inner_rings',[])])
add(g.buffer(0),o,'pour',o['layer'],o['pcb_copper_pour_id'])
# Antenna keepout is a physical no-copper region, including both GND pours.
for o in items:
if o['type']!='pcb_keepout':continue
assert o['shape']=='rect', 'Add geometry support before auditing another keepout shape'
x,y=o['center']['x'],o['center']['y']
region=box(x-o['width']/2,y-o['height']/2,x+o['width']/2,y+o['height']/2)
for g,n,kind,layer,label in shapes:
if layer in o['layers'] and region.intersection(g).area>1e-6:
violations.append({'kind':'copper_in_keepout','keepout':o['pcb_keepout_id'],
'copper':label,'layer':layer})
seen=set()
for layer in layers:
ss=[s for s in shapes if s[3]==layer];tree=STRtree([s[0] for s in ss])
for i,a in enumerate(ss):
for j in tree.query(a[0].buffer(.2)):
j=int(j)
if j<=i:continue
b=ss[j]
if a[1]==b[1]:continue
req=.15 if a[2]=='pad' and b[2]=='pad' else (.1 if layer_count==2 else .09) if a[2]=='track' and b[2]=='track' else .1
d=a[0].distance(b[0])
key=(layer,tuple(sorted([a[4],b[4]])))
if d<req-.0001 and key not in seen:
seen.add(key);violations.append({'kind':'copper_clearance','layer':layer,'a':a[4],'b':b[4],
'nets':[nets.get(a[1],a[1]),nets.get(b[1],b[1])],'actual':round(d,6),'required':req})
# Inner layers require 0.2mm to all copper; outer layers to tracks.
for hole,n,label in drills:
for j in tree.query(hole.buffer(.2)):
b=ss[int(j)]
if n==b[1] or (not layer.startswith('inner') and b[2]!='track'):continue
d=hole.distance(b[0]);key=(layer,label,b[4],'drill')
if d<.2-.0001 and key not in seen:
seen.add(key);violations.append({'kind':'drill_to_copper','layer':layer,'a':label,'b':b[4],'actual':round(d,6),'required':.2})
for i,a in enumerate(drills):
for b in drills[i+1:]:
if a[0].centroid.distance(b[0].centroid)<.0001 and a[1]==b[1]:continue
d=a[0].distance(b[0])
if d<.2-.0001:violations.append({'kind':'drill_spacing','a':a[2],'b':b[2],'actual':round(d,6),'required':.2})
# An unfilled drill intersecting an assembly land can wick solder away.
# No filled-and-capped process has been selected or approved for this project.
for hole,n,label in drills:
for g,pad_net,kind,layer,pad_label in shapes:
if kind=='pad' and hole.intersection(g).area>1e-6:
violations.append({'kind':'via_in_solder_land_requires_filled_capped_process',
'via':label,'pad':pad_label,'layer':layer})
# Check openings between component lands for the selected green solder mask.
pad_items={o['pcb_smtpad_id']:o for o in items if o['type']=='pcb_smtpad'}
mask_openings=[]
for g,n,kind,layer,label in shapes:
if kind=='pad':mask_openings.append((g.buffer(pad_items[label].get('soldermask_margin',0)),layer,label))
minimum_mask_bridge=1e9
for i,a in enumerate(mask_openings):
for b in mask_openings[i+1:]:
if a[1]!=b[1]:continue
d=a[0].distance(b[0]);minimum_mask_bridge=min(minimum_mask_bridge,d)
if d<.1-.0001:violations.append({'kind':'solder_mask_bridge','a':a[2],'b':b[2],'actual':d,'required':.1})
for opening,layer,label in mask_openings:
pad_net=net(pad_items[label])
for g,n,kind,z,other in shapes:
if z!=layer or n==pad_net or kind!='track':continue
d=opening.distance(g)
if d<.09-.0001:violations.append({'kind':'mask_to_track','a':label,'b':other,'actual':d,'required':.09})
# Aperture area/wall-area ratio for the specified 80um stencil.
minimum_paste_ratio=1e9
for o in items:
if o['type']!='pcb_solder_paste':continue
if o['shape']=='circle':ratio=o['radius']/(2*.08)
elif o['shape'] in ('rect','rotated_rect'):ratio=o['width']*o['height']/(2*(o['width']+o['height'])*.08)
else:raise ValueError('Unsupported paste geometry '+o['shape'])
minimum_paste_ratio=min(minimum_paste_ratio,ratio)
if ratio<.66:violations.append({'kind':'stencil_area_ratio','paste':o['pcb_solder_paste_id'],'actual':ratio,'required':.66})
# Verify conductive connectivity, independently of net labels and route endpoints.
physical=list(range(len(shapes)))
def group(i):
while physical[i]!=i:
physical[i]=physical[physical[i]];i=physical[i]
return i
def merge(i,j):physical[group(i)]=group(j)
for layer in layers:
ids=[i for i,s in enumerate(shapes) if s[3]==layer]
tree=STRtree([shapes[i][0] for i in ids])
for local,i in enumerate(ids):
for jj in tree.query(shapes[i][0].buffer(.001)):
j=ids[int(jj)]
if j>i and shapes[i][1]==shapes[j][1] and shapes[i][0].distance(shapes[j][0])<=.001:merge(i,j)
via_groups=collections.defaultdict(list)
for i,s in enumerate(shapes):
if s[2]=='via':via_groups[s[4]].append(i)
for ids in via_groups.values():
for i in ids[1:]:merge(ids[0],i)
net_pads=collections.defaultdict(list)
for i,s in enumerate(shapes):
if s[2]=='pad':net_pads[s[1]].append(i)
for n,ids in net_pads.items():
groups=collections.defaultdict(list)
for i in ids:groups[group(i)].append(shapes[i][4])
if len(groups)>1:violations.append({'kind':'physical_open_net','net':nets.get(n,n),'separate_copper_groups':list(groups.values())})
report={'circuit_sha256':hashlib.sha256(path.read_bytes()).hexdigest(),'counts':dict(collections.Counter(v['kind'] for v in violations)),
'minimum_mask_bridge_mm':round(minimum_mask_bridge,6),'minimum_stencil_area_ratio_80um':round(minimum_paste_ratio,6),'copper_primitives':len(shapes),'drills':len(drills),'violations':violations}
(root/'docs/fabrication-check.json').write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps({k:v for k,v in report.items() if k!='violations'},indent=2))
for v in violations[:25]:print(v)
sys.exit(bool(violations))