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-keyboard

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-enclosure-fit.py

"""Measure exported native triangles, including a complete 3.5 mm key press."""
from pathlib import Path
import sys,json,hashlib
import numpy as np
import trimesh
from shapely.geometry import MultiPoint,Polygon
from glb_geometry import GlbGeometry
ROOT=Path(__file__).resolve().parents[1]
half=sys.argv[1];folder=ROOT/f'outputs/{half}'
glb=GlbGeometry(folder/'keyboard-placement.glb')
geometry=json.loads((ROOT/'src/generated/mechanical-geometry.json').read_text())['halves'][half]
from functools import lru_cache
@lru_cache(None)
def printed(name):
    native=glb.mesh(name)
    solid=trimesh.load_mesh(ROOT/f'outputs/enclosure/{half}-{name.lower()}.stl')
    assert solid.is_watertight and solid.volume>0
    assert np.allclose(native.bounds,solid.bounds,atol=.002)
    assert abs(native.volume-solid.volume)<max(.02,solid.volume*2e-5),(name,native.volume,solid.volume)
    return solid
plate=printed('CASE_PLATE');base=printed('CASE_BASE')
case_plan=json.loads((ROOT/'src/generated/enclosure.json').read_text())['halves'][half]['parts']
plate_solids=next(p['solids'] for p in case_plan if p['name']=='CASE_PLATE')

def slab_envelope(mesh,lo,hi):
    # Convex XY envelope of all triangle edges clipped to this height slab.
    # Conservative even when a vendor OBJ has open or duplicate surfaces.
    v=mesh.vertices;inside=v[(v[:,2]>=lo)&(v[:,2]<=hi)]
    arrays=[inside[:,:2]]
    edges=v[mesh.edges_unique];a,b=edges[:,0],edges[:,1]
    for z in [lo,hi]:
        mask=(a[:,2]-z)*(b[:,2]-z)<0
        t=(z-a[mask,2])/(b[mask,2]-a[mask,2])
        arrays.append((a[mask]+t[:,None]*(b[mask]-a[mask]))[:,:2])
    points=np.concatenate(arrays)
    return MultiPoint(points).convex_hull if len(points) else Polygon()


def overlap(a,b):
    if np.any(a.bounds[1]<=b.bounds[0]+1e-5) or np.any(b.bounds[1]<=a.bounds[0]+1e-5):return 0.
    # An open supplier shell is replaced with a conservative convex solid.
    if not a.is_watertight:a=a.convex_hull
    if not b.is_watertight:b=b.convex_hull
    assert a.is_volume and b.is_volume
    result=trimesh.boolean.intersection([a,b],engine='manifold')
    if result.is_empty:return 0.
    volume=float(result.volume);assert np.isfinite(volume)
    return max(0.,volume)
checks=[]
def clear(name,a,b,limit=.002):
    volume=overlap(a,b)
    checks.append({'pair':name,'intersectionMm3':round(volume,6)})
    assert volume<limit,(name,volume)
for key in geometry['keys']:
    name=key['reference'];switch=glb.mesh(name+'_KEY');cap=glb.mesh(name+'_CAP')
    clear(name+' fixed switch / base',switch,base)
    for solid in plate_solids:
        lo=max(solid['z'],switch.bounds[0,2])
        hi=min(solid['z']+solid['height'],switch.bounds[1,2])
        levels=sorted(set([lo,hi]+[float(z) for z in switch.vertices[:,2] if lo<z<hi]))
        for low,high in zip(levels,levels[1:]):
            if high-low<1e-4:continue
            envelope=slab_envelope(switch,low+1e-5,high-1e-5)
            area=sum(envelope.intersection(Polygon(p['outer'],p['holes'])).area for p in solid['polygons'])
            checks.append({'pair':name+' switch / plate slab','zMm':[round(low,5),round(high,5)],'conservativeIntersectionMm2':round(area,6)})
            assert area<.002,(name,low,high,area)
    pressed=cap.copy();pressed.apply_translation([0,0,-3.5])
    clear(name+' full-press cap / plate',pressed,plate)
    for hole in geometry['mountingHoles'][2:]:
        bolt=glb.mesh('MOUNT_SCREW_'+hole['reference'])
        clear(name+' full-press cap / '+hole['reference']+' screw',pressed,bolt)
        clear(name+' fixed switch / '+hole['reference']+' screw',switch,bolt)
    for hole in geometry['mountingHoles'][2:]:
        spacer=printed('SPACER_'+hole['reference'])
        clear(name+' fixed switch / '+hole['reference']+' spacer',switch,spacer)

    # Preserve the actual cavity and prongs. A filled convex housing falsely
    # treats its plunger aperture as solid. C400230's red primitive is moving;
    # all remaining supplier surfaces are fixed housing/base/contacts.
    housing=glb.mesh(name+'_KEY',material_filter=lambda material:
        material.get('pbrMetallicRoughness',{}).get('baseColorFactor')!=[1,0,0,1])
    assert housing.bounds[1,2]<=5.801
    manager=trimesh.collision.CollisionManager();manager.add_object('fixed housing',housing)
    nominal=cap.copy();nominal.apply_translation([0,0,-3.0])
    collision=manager.in_collision_single(nominal)
    checks.append({'pair':name+' nominal 3.0 mm press / fixed housing surfaces',
                   'surfaceCollision':bool(collision),'gapMm':round(float(manager.min_distance_single(nominal)),6)})
    assert not collision,(name,'fixed housing at nominal switch stroke')
for name in ['LCD_GLASS','LCD_ACTIVE','LCD_FLEX','J_LCD','J_USB','SW_PWR','ENC1_KNOB','BATTERY_CELL','BATTERY_LABEL','J_NTC_WIRES']:
    mesh=glb.mesh(name)
    clear(name+' / base',mesh,base)
    clear(name+' / plate',mesh,plate)
# Check every exported bottom component whose XY/Z bounds enter the cell bay.
cell=glb.mesh('BATTERY_CELL');sources={e['source_component_id']:e for e in json.loads((folder/'keyboard.circuit.json').read_text()) if e['type']=='source_component'}
json_data=json.loads((folder/'keyboard.circuit.json').read_text());bottom=[]
for e in json_data:
    if e['type']!='pcb_component' or e['layer']!='bottom':continue
    name=sources[e['source_component_id']]['name']
    try:mesh=glb.mesh(name)
    except ValueError:continue
    clear(name+' / base',mesh,base)
    if np.all(cell.bounds[1]>mesh.bounds[0]) and np.all(mesh.bounds[1]>cell.bounds[0]):
        clear(name+' / cell',mesh,cell);bottom.append(name)
knob=glb.mesh('ENC1_KNOB');tip=glb.vertices('ENC1')[:,2].max()
assert abs(knob.bounds[1,2]-24)<.002
assert abs(knob.bounds[0,2]-14)<.002
flex=glb.vertices('LCD_FLEX');assert abs(np.ptp(flex[:,0])-9.47)<.002
tip_vertices=flex[flex[:,1]<4.02]
assert .295<np.ptp(tip_vertices[:,2])<.315
assert tip<=22.301,tip
assert knob.bounds[0,2]-.8>12.3
knob.apply_translation(-knob.bounds.mean(axis=0))
knob.export(ROOT/'outputs/enclosure/encoder-knob-14x10.stl')
# The native reference uses exactly the same board and cradle transforms.
tented=GlbGeometry(folder/'tenting-10deg.glb')
stand=tented.mesh(f'TENTING_{half.upper()}_10')
assert stand.is_watertight and stand.volume>0
tented_base=base.copy();pose=json.loads((ROOT/'src/generated/tenting.json').read_text())['halves'][half]['10']
tented_base.apply_transform(trimesh.transformations.rotation_matrix(np.deg2rad(pose['rotationYDegrees']),[0,1,0]))
tented_base.apply_translation([0,0,pose['liftZ']])
assert np.allclose(tented_base.bounds,tented.mesh('CASE_BASE').bounds,atol=.003)

clear('10 degree cradle / case',stand,tented_base,limit=.03)
for angle in [5,10,15]:
    cradle=trimesh.load_mesh(ROOT/f'outputs/enclosure/{half}-tenting-{angle}deg.stl')
    assert cradle.is_volume
    pose=json.loads((ROOT/'src/generated/tenting.json').read_text())['halves'][half][str(angle)]
    transform=trimesh.transformations.rotation_matrix(np.deg2rad(pose['rotationYDegrees']),[0,1,0])
    transform[:3,3]=[0,0,pose['liftZ']]
    posed=base.copy();posed.apply_transform(transform)
    clear(f'{angle} degree cradle / case STL',cradle,posed,limit=.03)
    for name,y,size,z in [('USB plug',20,[16,11,7],-2.2),('power access',4,[16,8,5],-1.8)]:
        corridor=trimesh.creation.box(extents=size)
        corridor.apply_translation([72 if half=='left' else -72,y,z])
        clear(name+' / case',corridor,base)
        corridor.apply_transform(transform)
        clear(f'{angle} degree cradle / '+name,cradle,corridor)

report={'passed':True,'method':'Native GLB triangles; matching watertight case STLs for booleans; conservative clipped-slab envelopes for open vendor switch shells and convex solids for other open vendor shells; full key travel','maximumKeyTravelMm':3.5,'fixedHousingNominalStrokeMm':3.0,'encoderTipZMm':round(float(tip),4),'knobTopZMm':24,'previousKnobTopZMm':28,'knobBottomZMm':14,'knobNeckClearanceAtFullPushMm':.9,'keycapAtRestZMm':[round(float(glb.vertices('SW1_CAP')[:,2].min()),4),round(float(glb.vertices('SW1_CAP')[:,2].max()),4)],'keycapAtFullPressZMm':[round(float(glb.vertices('SW1_CAP')[:,2].min()-3.5),4),round(float(glb.vertices('SW1_CAP')[:,2].max()-3.5),4)],'batteryNominalMm':[29,36,4.75],'caseFastener':'M2 x 12, head <=3.5 mm OD / <=1.3 mm high','keycapProfile':'KLP Lame Choc size','bottomPartsEnteringBatteryBounds':bottom,'checks':checks,'glbSha256':hashlib.sha256(glb.raw).hexdigest(),'circuitJsonSha256':hashlib.sha256((folder/'keyboard.circuit.json').read_bytes()).hexdigest(),'physicalFitTested':False,'limitations':'Sourced KLP keycap and raw-panel CAD, supplier switch and connector models; nominal cell and encoder dimensions; FPC pin-1/contact engagement, stem tolerances, the actual switch travel tolerance endpoint, printing tolerances and stability need a physical prototype.'}
(folder/'enclosure-fit-check.json').write_text(json.dumps(report,indent=2)+'\n')
print(half,'exported-mesh fit checks passed:',len(checks),'pairs; knob top 24 mm')