rushabhcodes/wireless-split-keyboard
Wireless Split Keyboard — custom routed nRF52840 split PCBs with a printable enclosure
- Version
- 0.4.5
- License
- unset
- Stars
- 0
Use with the tscircuit CLI
tsci is the tscircuit CLI. Install it with npm install -g tscircuit.
tsci clone rushabhcodes/wireless-split-keyboard # download the package files into ./wireless-split-keyboard
tsci add rushabhcodes/wireless-split-keyboard # add it to your project as @tsci/rushabhcodes.wireless-split-keyboardIn 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-socket-models.py
"""Measure actual exported socket meshes against native pads and drills.
GLB model vertices, rather than JSX transforms, are the independent evidence.
"""
from pathlib import Path
import sys,json,struct,argparse,hashlib
import numpy as np
from shapely.geometry import Point,MultiPoint
from routing_model import BoardModel
p=argparse.ArgumentParser();p.add_argument('half');p.add_argument('--circuit');p.add_argument('--model');p.add_argument('--output');p.add_argument('--report-only',action='store_true');args=p.parse_args()
root=Path(__file__).resolve().parents[1];half=args.half
model=Path(args.model or root/f'outputs/{half}/keyboard-placement.glb');circuit=Path(args.circuit or root/f'outputs/{half}/keyboard.circuit.json')
m=BoardModel(circuit);raw=model.read_bytes();n=struct.unpack_from('<I',raw,12)[0];g=json.loads(raw[20:20+n]);binary=28+n
DTYPES={5120:'i1',5121:'u1',5122:'<i2',5123:'<u2',5125:'<u4',5126:'<f4'}
COUNTS={'SCALAR':1,'VEC2':2,'VEC3':3,'VEC4':4,'MAT4':16}
def accessor(i):
a=g['accessors'][i];v=g['bufferViews'][a['bufferView']];dtype=np.dtype(DTYPES[a['componentType']]);count=COUNTS[a['type']]
start=binary+v.get('byteOffset',0)+a.get('byteOffset',0)
return np.ndarray((a['count'],count),dtype=dtype,buffer=raw,offset=start,strides=(v.get('byteStride',dtype.itemsize*count),dtype.itemsize)).copy().astype(float)
def transform(node):
if 'matrix' in node:return np.array(node['matrix']).reshape((4,4)).T
x,y,z,w=node.get('rotation',[0,0,0,1]);r=np.eye(4)
r[:3,:3]=[[1-2*(y*y+z*z),2*(x*y-z*w),2*(x*z+y*w)],[2*(x*y+z*w),1-2*(x*x+z*z),2*(y*z-x*w)],[2*(x*z-y*w),2*(y*z+x*w),1-2*(x*x+y*y)]]
r[:3,:3]@=np.diag(node.get('scale',[1,1,1]));r[:3,3]=node.get('translation',[0,0,0]);return r
world={}
def walk(i,parent):
world[i]=parent@transform(g['nodes'][i])
for child in g['nodes'][i].get('children',[]):walk(child,world[i])
for node in g['scenes'][g.get('scene',0)]['nodes']:walk(node,np.eye(4))
results=[]
for i,node in enumerate(g['nodes']):
ref=node.get('extras',{}).get('tscircuit',{}).get('componentName',node.get('name',''))
if not ref.startswith('SW') or not ref[2:].isdigit() or i not in world:continue
component=next(c for c in m.components.values() if m.sources[c['source_component_id']]['name']==ref)
origin=component['footprint_origin'];theta=np.deg2rad(component['rotation']);ct,st=np.cos(theta),np.sin(theta)
plastic=[];metal=[]
for primitive in g['meshes'][node['mesh']]['primitives']:
v=accessor(primitive['attributes']['POSITION']);v=(np.c_[v,np.ones(len(v))]@world[i].T)[:,:3]
v=v[:,[0,2,1]]*[-1,1,1] # glTF to native PCB XYZ
color=g['materials'][primitive['material']]['pbrMetallicRoughness']['baseColorFactor'][:3]
if max(abs(c-.250980392) for c in color)<.02:plastic.append(v)
if max(abs(c-.752941176) for c in color)<.02:metal.append(v)
assert plastic and metal,ref+': exact supplier socket mesh is missing'
plastic=np.concatenate(plastic);metal=np.concatenate(metal)
tip=plastic[plastic[:,2]>plastic[:,2].max()-1e-4,:2];tip=np.unique(np.round(tip,6),axis=0)
distance=((tip[:,None,:]-tip[None,:,:])**2).sum(2);a,b=np.unravel_index(distance.argmax(),distance.shape);centers=tip[[a,b]]
for _ in range(20):
labels=((tip[:,None,:]-centers[None,:,:])**2).sum(2).argmin(1);next_centers=np.array([tip[labels==k].mean(0) for k in [0,1]])
if np.max(abs(next_centers-centers))<1e-8:break
centers=next_centers
pegs=[]
for k in [0,1]:
hull=np.array(MultiPoint(tip[labels==k]).convex_hull.exterior.coords)[:-1]
# Circle fit using a centered frame to avoid loss of accuracy far from origin.
pivot=hull.mean(0);h=hull-pivot
x,y,c=np.linalg.lstsq(np.c_[2*h[:,0],2*h[:,1],np.ones(len(h))],(h*h).sum(1),rcond=None)[0]
pegs.append(pivot+[x,y])
holes=[Point(h['x'],h['y']) for h in m.bytype['pcb_hole'] if h.get('pcb_component_id')==component['pcb_component_id'] and abs(h['hole_diameter']-3)<.001]
assert len(holes)==2,ref
peg_errors=[min(Point(xy).distance(h) for h in holes) for xy in pegs]
u=metal[:,:2]-[origin['x'],origin['y']];local_x=ct*u[:,0]+st*u[:,1]
wing=metal[np.abs(local_x)>4.774,:2]
pads=[pad['shape'] for pad in m.byref[ref]];outside=[];margins=[]
for xy in wing:
point=Point(xy);cover=[pad for pad in pads if pad.buffer(.002).covers(point)]
if not cover:outside.append(min(point.distance(pad) for pad in pads))
else:margins.append(max(point.distance(pad.boundary) for pad in cover))
results.append({'ref':ref,'pegToDrillMaxErrorMm':round(max(peg_errors),6),'metalWingVerticesOutsidePads':len(outside),'maximumMetalOverhangMm':round(max(outside,default=0),6),'minimumLandMarginMm':round(min(margins,default=0),6),'pegTipZ':round(float(plastic[:,2].max()),6)})
assert len(results)==29,(half,len(results))
passed=all(r['pegToDrillMaxErrorMm']<.002 and r['metalWingVerticesOutsidePads']==0 and r['minimumLandMarginMm']>.1 for r in results)
report={'half':half,'passed':passed,'circuitJsonSha256':hashlib.sha256(circuit.read_bytes()).hexdigest(),'glbSha256':hashlib.sha256(raw).hexdigest(),'method':'Actual exported GLB geometry: fit both plastic locating-post tips to native 3 mm drills; require all outer solder-leg mesh vertices inside their pads with >0.1 mm land margin','sockets':results,'maximumPegErrorMm':max(r['pegToDrillMaxErrorMm'] for r in results),'minimumLandMarginMm':min(r['minimumLandMarginMm'] for r in results)}
output=Path(args.output or root/f'outputs/{half}/socket-model-check.json');output.write_text(json.dumps(report,indent=2)+'\n')
print(half,'passed',passed,'socket count',len(results),'max peg error',report['maximumPegErrorMm'],'min metal margin',report['minimumLandMarginMm'])
for r in results:
if r['pegToDrillMaxErrorMm']>.002 or r['metalWingVerticesOutsidePads']:print(r)
if not passed and not args.report_only:sys.exit(1)