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/generate-enclosure.py
"""Author the printable enclosure plan consumed as native JSCAD by tscircuit.
The hosted build needs only the committed plan and TSX; Python exports STL/QA.
"""
from pathlib import Path
import json,math,subprocess,shutil
from shapely.geometry import Polygon,Point,box,LineString
from shapely.affinity import rotate,translate
from shapely.ops import unary_union
import trimesh
ROOT=Path(__file__).resolve().parents[1]
OUT=ROOT/'outputs/enclosure';OUT.mkdir(parents=True,exist_ok=True)
geometry=json.loads((ROOT/'src/generated/mechanical-geometry.json').read_text())
bun=shutil.which('bun') or str(Path.home()/'.bun/bin/bun')
placements=json.loads(subprocess.check_output([bun,'-e',
'import {placement,offsetPlacement} from "./src/componentPlacement"; console.log(JSON.stringify(Object.fromEntries(["left","right"].map(h=>[h,Object.fromEntries(["SW_PWR","J_USB","SW_RESET_BODY"].map(r=>[r,r==="SW_RESET_BODY"?offsetPlacement(h,r,"SW_RESET",0,h==="right"?1.4:1.5):placement(h,r,{x:0,y:0,rotation:0,side:"top"})]))]))))'],cwd=ROOT))
PARAMS={'pcbClearance':.35,'wall':1.8,'floorBottom':-10.8,'floorThickness':1.8,
'boardBottom':-.8,'boardTop':.8,'plateBottom':1.8,'plateThickness':1.2,
'batteryWidth':29,'batteryHeight':36,'batteryThickness':4.75,'batteryBayClearance':.5,
'mountScrew':'M2 x 12, head OD <=3.5, height <=1.3','basePilotDiameter':1.6,'plateClearanceDiameter':2.2,
'switchTravel':1.5,'switchActuatorOutreach':3.385,'switchAccessWidth':12,
'panelBodyWidth':14,'panelBodyHeight':32,'panelWindowWidth':11.5,'panelWindowHeight':26,
'panelCenterX':53.3,'panelSeatZ':1.8,'usbBodyBottomAllocationZ':-4.1,'portWindowBottomZ':-6,'portWindowTopZ':1.8}
plan={'version':3,'units':'mm','parameters':PARAMS,'halves':{}}
qa={'status':'CAD-validated prototype; physical fit pending','halves':{}}
def polygons(g):
return [g] if g.geom_type=='Polygon' else [p for p in g.geoms if p.geom_type=='Polygon']
def ring(coords):
v=[(round(x,6),round(y,6)) for x,y in list(coords)[:-1]]
area=sum(a[0]*b[1]-b[0]*a[1] for a,b in zip(v,v[1:]+v[:1]))
return v if area>0 else v[::-1]
def serialize(g):return [{'outer':ring(p.exterior.coords),'holes':[ring(h.coords) for h in p.interiors]} for p in polygons(g)]
def solid(g,z,height):return {'z':z,'height':height,'polygons':serialize(g)}
def mesh_for(solids):
meshes=[]
for s in solids:
for p in s['polygons']:
g=Polygon(p['outer'],p['holes']);m=trimesh.creation.extrude_polygon(g,s['height'],engine='earcut');m.apply_translation([0,0,s['z']]);meshes.append(m)
return trimesh.boolean.union(meshes,engine='manifold') if len(meshes)>1 else meshes[0]
for half in ['left','right']:
g=geometry['halves'][half];pcb=Polygon([(p['x'],p['y']) for p in g['outline']])
sign=1 if half=='left' else -1
inner=pcb.buffer(PARAMS['pcbClearance'],quad_segs=8)
outer=pcb.buffer(PARAMS['pcbClearance']+PARAMS['wall'],quad_segs=8)
wall=outer.difference(inner)
mounts=g['mountingHoles'][2:]
pilot=unary_union([Point(h['x'],h['y']).buffer(.8,quad_segs=16) for h in mounts])
clear=unary_union([Point(h['x'],h['y']).buffer(1.1,quad_segs=16) for h in mounts])
# Bottom-mounted connectors exit through the lower side wall.
usb=placements[half]['J_USB'];sw=placements[half]['SW_PWR']
def access(y,width):return box(58 if sign>0 else -82,y-width/2,82 if sign>0 else -58,y+width/2)
switch_cut=access(sw['y'],PARAMS['switchAccessWidth']);usb_cut=access(usb['y'],12)
both=switch_cut.union(usb_cut)
# Floor, lower rim, connector-level rim, and upper rim are stacked solids.
reset=placements[half]['SW_RESET_BODY']
reset_access=Point(reset['x'],reset['y']).buffer(1.5,quad_segs=24)
floor=outer.difference(pilot.union(reset_access))
base=[solid(floor,-10.8,1.8),solid(wall,-9,3),solid(wall.difference(both),-6,7.8)]
for h in mounts:
post=Point(h['x'],h['y']).buffer(2.4,quad_segs=24).difference(Point(h['x'],h['y']).buffer(.8,quad_segs=16))
base.append(solid(post,-9,8.2))
# Battery sits below the key field, away from the antenna/controller cluster.
bx=-8 if half=='left' else 8;by=5
bay_inner=box(bx-15,by-18.5,bx+15,by+18.5)
bay_outer=box(bx-16,by-19.5,bx+16,by+19.5)
cable_gap=box(bx+(14 if sign>0 else -18),by-3,bx+(18 if sign>0 else -14),by+3)
rails=bay_outer.difference(bay_inner).difference(cable_gap)
assert inner.covers(bay_outer)
assert all(bay_outer.distance(Point(h['x'],h['y']))>3.2 for h in mounts)
base.append(solid(rails,-9,1.5))
# Retention strap slots run outside the battery footprint through the floor.
strap_slots=unary_union([box(bx-17.5,y-1,bx-16,y+1) for y in [by-10,by+10]]+[box(bx+16,y-1,bx+17.5,y+1) for y in [by-10,by+10]])
base[0]=solid(floor.difference(strap_slots),-10.8,1.8)
keys=[translate(rotate(box(-7,-7,7,7),k['rotation'],origin=(0,0)),k['x'],k['y']) for k in g['keys']]
enc=g['encoder'];encoder_cut=box(enc['x']-7.5,enc['y']-7.5,enc['x']+7.5,enc['y']+7.5)
px=PARAMS['panelCenterX']*sign;py=29
panel_pocket=box(px-7.2,py-16.2,px+7.2,py+16.2)
panel_window=box(px-5.75,30.173-13,px+5.75,30.173+13)
# The detailed panel model has a 9.47 mm-wide root before narrowing to its
# 5.5 mm finished tail. Clear the entire FPC, including the shoulder at the glass.
flex_channel=box(px-4.95,-2,px+4.95,14)
common=unary_union(keys+[encoder_cut,clear,flex_channel])
bezel=box(px-8,py-17,px+8,py+17)
bezel_ring=bezel.difference(panel_pocket).difference(flex_channel)
support=bezel.difference(panel_window).difference(flex_channel)
plate=[solid(outer.difference(common.union(panel_pocket)),1.8,1.2),
solid(bezel_ring,1.4,1.4),
solid(support,1.4,.2),
solid(bezel.difference(panel_window).difference(flex_channel),2.8,1.0)]
parts=[{'name':'CASE_BASE','label':'Enclosure base','color':'#263b4d','solids':base},
{'name':'CASE_PLATE','label':'Key plate and display carrier','color':'#d7dde5','solids':plate}]
for h in mounts:
spacer=Point(h['x'],h['y']).buffer(2.8,quad_segs=24).difference(Point(h['x'],h['y']).buffer(1.1,quad_segs=16))
collar=Point(h['x'],h['y']).buffer(1.95,quad_segs=24).difference(Point(h['x'],h['y']).buffer(1.1,quad_segs=16))
parts.append({'name':'SPACER_'+h['reference'],'label':'M2 PCB-to-plate spacer with centering collar','color':'#d5a04b','solids':[solid(spacer,.8,1.0),solid(collar,-.6,1.4)]})
models={};part_qa={}
for p in parts:
mesh=mesh_for(p['solids']);assert mesh.is_watertight and mesh.volume>0
mesh.export(OUT/f'{half}-{p["name"].lower()}.stl');models[p['name']]=mesh
part_qa[p['name']]={'watertight':bool(mesh.is_watertight),'volumeMm3':round(float(mesh.volume),3),'bounds':mesh.bounds.tolist()}
# Confirm an unobstructed path at both actuator end positions.
access_checks=[]
for delta in [-.75,.75]:
y=sw['y']+delta;actuator_x=sw['x']+sign*PARAMS['switchActuatorOutreach']
ray=LineString([(actuator_x,y),(sign*75,y)]).buffer(.4)
at_height=unary_union([Polygon(p['outer'],p['holes']) for s in base if s['z']<-1.8<s['z']+s['height'] for p in s['polygons']])
area=ray.intersection(at_height).area;assert area<1e-7
edge=pcb.intersection(LineString([(-100,y),(100,y)])).bounds[2 if sign>0 else 0]
access_checks.append({'position':delta,'actuatorBeyondPcbEdgeMm':round(sign*(actuator_x-edge),4),'caseObstructionMm2':round(area,8)})
# USB plug corridor at the receptacle's underside height.
usb_ray=LineString([(usb['x'],usb['y']),(sign*75,usb['y'])]).buffer(5.5)
usb_obstruction=0
for probe_z in [-5.7,-2.2,1.3]:
port_wall=unary_union([Polygon(p['outer'],p['holes']) for s in base if s['z']<probe_z<s['z']+s['height'] for p in s['polygons']])
usb_obstruction+=usb_ray.intersection(port_wall).area
assert usb_obstruction<1e-7
reset_probe=Point(reset['x'],reset['y']).buffer(.8)
reset_obstruction=sum(reset_probe.intersection(Polygon(p['outer'],p['holes'])).area for s in base for p in s['polygons'])
assert reset_obstruction<1e-7
# Base posts and upper spacers meet at the intended PCB faces.
scene=trimesh.Scene()
for name,mesh in models.items():scene.add_geometry(mesh,node_name=name)
scene.export(OUT/f'{half}-enclosure.glb')
plan['halves'][half]={'switch':sw,'usb':usb,'batteryCenter':[bx,by],'parts':parts}
qa['halves'][half]={'pcbEdgeClearanceMm':.35,'primaryMounts':5,'switchAccess':access_checks,'batteryNominalMm':[29,36,4.75],'batteryTopZ':-4.25,'panelFit':'14 x 32 x 0.745 mm glass on 0.2 mm adhesive, gently curved 13.63 mm FPC to top connector','panelBottomZ':1.8,'panelSupportZ':1.6,'panelAdhesiveThicknessMm':.2,'panelXYClearancePerSideMm':.2,'panelUpperLipClearanceMm':.255,'panelSupportAreaMm2':round(support.intersection(box(px-7,13,px+7,45)).area,3),'panelWindowActiveClearanceMm':[.378,.36],'flexChannelWidthMm':9.9,'flexMaximumNeckWidthMm':9.47,'flexStiffenerWidthMm':5.5,'keycapFullTravelMm':3.5,'keycapProfile':'KLP Lame Choc stem / Choc size, unscaled upstream CAD','usbBodyBottomAllocationZ':-4.1,'portWindowZ':[-6,1.8],'usbPlugEnvelopeMm':[11,7],'usbAccessObstructionMm2':round(usb_obstruction,8),'resetAccessObstructionMm2':round(reset_obstruction,8),'resetAccessDiameterMm':3,'resetAccessCenter':[reset['x'],reset['y']], 'panelToUsbVerticalClearanceMm':1.6,'parts':part_qa}
(ROOT/'src/generated/enclosure.json').write_text(json.dumps(plan,separators=(',',':'))+'\n')
(OUT/'clearance-check.json').write_text(json.dumps(qa,indent=2)+'\n')
print(json.dumps({h:{'parts':len(plan['halves'][h]['parts']),'switchAccess':qa['halves'][h]['switchAccess']} for h in ['left','right']},indent=2))