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/extract_geometry.py
"""Extract *mechanical measurements only* from pinned upstream PCB.
The reversible reference represents the right half. SW25 is an alternative to
SW31 at the SAME coordinate and is deliberately excluded in encoder builds.
Tracks, vias, zones, module electrical nets and controller boards are not used.
"""
from pathlib import Path
import json,math,hashlib
from sexpr import parse,field,fields
ROOT=Path(__file__).resolve().parents[1]
SOURCE=ROOT/'references/sofle/SofleChocWireless/PCB/SofleKeyboard.kicad_pcb'
COMMIT='aae7cc0ac5ca563dab8222320ae8749ed1911e56'
def extract():
pcb=parse(SOURCE.read_text())
footprints={field(f,'fp_text')[1]:f for f in fields(pcb,'footprint')}
edges=[]
for kind in ('gr_line','gr_arc'):
for item in fields(pcb,kind):
if field(item,'layer')!=['Edge.Cuts']:continue
e={'kind':kind[3:]}
for key in ('start','mid','end'):
if field(item,key):e[key]=field(item,key)[:2]
edges.append(e)
def tessellate(e):
if e['kind']=='line':return [e['start'],e['end']]
a,b,c=e['start'],e['mid'],e['end']
ax,ay=a;bx,by=b;cx,cy=c
den=2*(ax*(by-cy)+bx*(cy-ay)+cx*(ay-by))
ux=((ax*ax+ay*ay)*(by-cy)+(bx*bx+by*by)*(cy-ay)+(cx*cx+cy*cy)*(ay-by))/den
uy=((ax*ax+ay*ay)*(cx-bx)+(bx*bx+by*by)*(ax-cx)+(cx*cx+cy*cy)*(bx-ax))/den
r=math.hypot(ax-ux,ay-uy)
angles=[math.atan2(y-uy,x-ux) for x,y in (a,b,c)]
sweep=(angles[2]-angles[0])%(2*math.pi)
if (angles[1]-angles[0])%(2*math.pi)>sweep:sweep-=2*math.pi
# Maximum chord sagitta 0.005 mm; source arcs are retained separately.
n=max(2,math.ceil(abs(sweep)/(2*math.acos(1-min(0.005/r,1)))))
return [a]+[[ux+r*math.cos(angles[0]+sweep*i/n),uy+r*math.sin(angles[0]+sweep*i/n)] for i in range(1,n)]+[c]
remaining=[tessellate(e) for e in edges]; contour=remaining.pop(0)
while remaining:
for i,line in enumerate(remaining):
if math.dist(contour[-1],line[0])<1e-4:break
if math.dist(contour[-1],line[-1])<1e-4:line=list(reversed(line));break
else:raise ValueError(f'Disconnected outline at {contour[-1]}')
contour+=line[1:];remaining.pop(i)
assert math.dist(contour[0],contour[-1])<1e-4
contour=contour[:-1]
xmin=min(p[0] for p in contour);xmax=max(p[0] for p in contour)
ymin=min(p[1] for p in contour);ymax=max(p[1] for p in contour)
origin=[(xmin+xmax)/2,(ymin+ymax)/2]
def xy(x,y,side):return {'x':round((x-origin[0])*(1 if side=='right' else -1),7),'y':round(origin[1]-y,7)}
def placement(ref,side):
at=field(footprints[ref],'at');rot=at[2] if len(at)>2 else 0
return {'reference':ref,**xy(*at[:2],side),'rotation':(rot if side=='right' else 180-rot)%360,'source':{'x':at[0],'y':at[1],'rotation':rot}}
halves={}
for side in ('left','right'):
keys=[]
for n in range(1,31):
if n==25:continue
p=placement(f'SW{n}',side)
p.update({'row':(n-1)//6,'column':(n-1)%6})
keys.append(p)
holes=[]
for n in range(1,8):
ref=f'TH{n}';pad=fields(footprints[ref],'pad')[0]
at=field(footprints[ref],'at');local=field(pad,'at')
angle=math.radians(at[2] if len(at)>2 else 0)
hx=at[0]+local[0]*math.cos(angle)+local[1]*math.sin(angle)
hy=at[1]-local[0]*math.sin(angle)+local[1]*math.cos(angle)
holes.append({**placement(ref,side),**xy(hx,hy,side),'sourceCenter':{'x':hx,'y':hy},
'diameter':field(pad,'drill')[0], 'plated':pad[2]=='thru_hole','padDiameter':field(pad,'size')[0]})
halves[side]={'outline':[xy(*p,side) for p in contour], 'keys':keys,'mountingHoles':holes,
'encoder':{**placement('SW31',side),'row':4,'column':0},
'displayHeaderReference':placement('J3',side),'formerControllerReference':placement('U1',side)}
return {'source':{'repository':'https://github.com/db-ok/SofleChocWireless','commit':COMMIT,'path':str(SOURCE.relative_to(ROOT)),
'sha256':hashlib.sha256(SOURCE.read_bytes()).hexdigest(),'license':'MIT','originKiCadMm':origin,
'axes':'right: x=X-originX,y=originY-Y; left: mirror x. tscircuit rotations are CCW.',
'arcChordToleranceMm':0.005},'dimensions':{'width':xmax-xmin,'height':ymax-ymin},'sourceEdges':edges,'halves':halves}
if __name__=='__main__':
result=extract(); out=ROOT/'src/generated/mechanical-geometry.json';out.parent.mkdir(exist_ok=True)
out.write_text(json.dumps(result,indent=2)+'\n')
print(json.dumps({'dimensions':result['dimensions'],'edgeCount':len(result['sourceEdges']),'vertices':len(result['halves']['right']['outline']),
'keysPerHalf':len(result['halves']['right']['keys']),'mountsPerHalf':len(result['halves']['right']['mountingHoles'])},indent=2))