MustafaMulla29/rp2040-bldc-motor-controller

Hardware assembly metadata and PCB geometry for a controller board with a snap-off rotary-encoder section, plus four parallel 150 µF/50 V bulk electrolytic capacitors filtering the motor supply.

Version
2.0.40
License
unset
Stars
0

Use with the tscircuit CLI

tsci is the tscircuit CLI. Install it with npm install -g tscircuit.

tsci clone MustafaMulla29/rp2040-bldc-motor-controller  # download the package files into ./rp2040-bldc-motor-controller
tsci add MustafaMulla29/rp2040-bldc-motor-controller    # add it to your project as @tsci/MustafaMulla29.rp2040-bldc-motor-controller

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.

enclosure/verify.py

"""Independent solid intersections against the current PCB and mating envelopes.
These checks establish modeled clearance, not supplier tolerances or a physical fit.
"""
from pathlib import Path
import json,hashlib,os
import numpy as np
import manifold3d as mf
import trimesh
from export_solid import evaluate
from verify_usb import verify_usb
ROOT=Path(__file__).parent
OUT=ROOT/os.environ.get("ENCLOSURE_OUTPUT_DIR","dist")
LAYOUT=OUT.name=="layout-dist"
REFERENCE=OUT if LAYOUT else ROOT/"reference-models"
PCB_INPUT=ROOT/(json.loads((OUT/"build-report.json").read_text())["pcbInput"] if LAYOUT else "../dist/pcb/circuit.json")

def box(lo,hi):
 lo=np.array(lo,dtype=float);hi=np.array(hi,dtype=float)
 if np.any(hi-lo<.00001):return mf.Manifold()
 return mf.Manifold.cube((hi-lo).tolist(),center=True).translate(((lo+hi)/2).tolist())
def cyl(x,y,z0,z1,r):return mf.Manifold.cylinder(z1-z0,r,circular_segments=48).translate([x,y,z0])
def verify_power_recess(solids,design,envelopes,pcb,checks,check,metric):
    """Console-style side lever through the case wall; no separate printed actuator."""
    p=design['power'];lid=solids['lid'];base=solids['base']
    outer=-12.5-91/2-design['boardClearance']-design['wall'];inner=outer+design['wall']
    half=p['leverWidth']/2+p['travel']/2
    metric('POWER lever stands proud of the outer case surface',outer-p['leverTipX'],1.5)
    metric('POWER lever stands proud of the thumb-pocket floor',outer+p['pocketDepth']-p['leverTipX'],3.0)
    metric('POWER wall slot clears full lever travel each side',p['slotHalfWidth']-half,.3)
    metric('POWER wall slot clears lever top',p['slotTop']-p['leverTop'],.3)
    metric('POWER base tongue stays below the lever',p['leverBottom']-p['tongueTop'],.3)
    metric('POWER switch body clears the case wall',p['bodyFaceX']-inner,3.0)
    # Fingertip pad pressing the lever sideways in both end positions, inside the pocket.
    for side,y0 in (('toward ON',p['y']+p['travel']/2+p['leverWidth']/2+.05),('toward OFF',p['y']-p['travel']/2-p['leverWidth']/2-.05)):
        sgn=1 if side=='toward ON' else -1
        pad=box([p['leverTipX']+.05,min(y0,y0+sgn*4),p['leverBottom']],[outer+p['pocketDepth']-.1,max(y0,y0+sgn*4),p['leverTop']])
        check(f'POWER fingertip pushes lever {side} / lid',(pad^lid).volume())
        check(f'POWER fingertip pushes lever {side} / base',(pad^base).volume())
    # The slot below the lever is closed by the base tongue (no open gap into the case).
    gap=box([outer+p['pocketDepth']+.1,p['y']-p['slotHalfWidth']+.15,design['floorTop']+.2],[inner-.2,p['y']+p['slotHalfWidth']-.15,p['tongueTop']-.1])
    check('POWER slot below lever filled by base tongue',(gap-base).volume())
    return {'leverProudOfCaseMm':round(outer-p['leverTipX'],3),'leverProudOfPocketMm':round(outer+p['pocketDepth']-p['leverTipX'],3),
            'limit':'SK-22D03-G080 lever length and section from the supplier footprint drawing (no supplier 3D model); simplified CAD. Switch force, detent feel and ON/OFF contact sense need a first-fit check.'}


def verify_mount_flanges(solids,design,body,report,check,condition,metric):
    """Two mounting flanges: the floor plate extended past the POWER/USB wall and the encoder wall."""
    m=design['mount'];lid=solids['lid'];base=solids['base'];bottom=design['bottom'];top=design['floorTop']
    left=body['x']-body['width']/2;right=body['x']+body['width']/2
    front=body['y']-body['depth']/2;rear=body['y']+body['depth']/2
    holes=report['mountHoles']
    condition('Four mounting holes, two in each flange',len(holes)==4 and sum(1 for x,_ in holes if x<left)==2 and sum(1 for x,_ in holes if x>right)==2)
    bounds=report['parts']['base']['bounds']
    condition('Flanges are flush with the underside',abs(bounds[0][2]-bottom)<1e-6)
    metric('Flange width past each side wall',min(left-bounds[0][0],bounds[1][0]-right),m['width'])
    for side,x0,x1 in (('POWER / USB side',left-m['width'],left),('encoder side',right,right+m['width'])):
        # Nothing of the base stands above the flange, so it prints flat and a screwdriver has a clear run.
        lo=x0-.5 if x1<=left else x0+.02;hi=x1-.02 if x1<=left else x1+.5
        check(f'Flange on the {side} is a flat plate, nothing above it',(box([lo,front-.5,top+.02],[hi,rear+.5,top+40])^base).volume())
    usb=next(o for o in report['portOpenings'] if o['name']=='USB');pw=design['power'];enc=design['encoder']
    for i,(x,y) in enumerate(holes,1):
        name=f'Mounting hole {i} at ({x:.1f}, {y:.1f})'
        check(name+' / M4 screw passes through',(cyl(x,y,bottom-1,top+1,2.0)^base).volume())
        washer=cyl(x,y,bottom+.1,top-.1,m['washerRadius'])-cyl(x,y,bottom-1,top+1,m['holeRadius']+.01)
        check(name+' / flange supports the whole 9 mm washer',(washer-base).volume())
        head=cyl(x,y,top+.02,top+4.5,m['washerRadius'])
        check(name+' / washer and pan head clear the lid',(head^lid).volume())
        check(name+' / washer and pan head clear the base',(head^base).volume())
        wall=left if x<left else right
        metric(name+' / washer edge to the side wall',abs(x-wall)-m['washerRadius'],1.5)
        metric(name+' / hole edge to the flange outer edge',m['width']-m['holeOffset']-m['holeRadius'],3.0)
        metric(name+' / hole edge to the front or rear edge',min(y-front,rear-y)-m['holeRadius'],3.0)
        if x<left:
            metric(name+' / washer clear of the USB opening along the wall',abs(y-usb['y'])-usb['depth']/2-usb['leadInFlare']-m['washerRadius'],3.0)
            metric(name+' / washer clear of the POWER thumb pocket along the wall',abs(y-pw['y'])-pw['pocketHalfDepth']-m['washerRadius'],3.0)
        else:
            metric(name+' / washer clear of the encoder opening along the wall',abs(y-enc['y'])-enc['depth']/2-m['washerRadius'],3.0)
    # Cables and fingers work above the flange: lowest edges of the side openings against the flange top.
    metric('USB opening floor above the flange top',usb['bottom']-top,3.0)
    metric('POWER thumb pocket floor above the flange top',pw['pocketBottom']-top,3.0)
    metric('Encoder opening floor above the flange top',enc['bottom']-top,3.0)
    return {'holes':holes,'holeDiameterMm':2*m['holeRadius'],'flangeWidthMm':m['width'],'thicknessMm':top-bottom,
            'overallWidthMm':round(bounds[1][0]-bounds[0][0],3),
            'limit':'Modelled only. Screw size, plate stiffness and the surface it is fixed to are not qualified; a 2.4 mm printed plate should not be over-tightened.'}


def main():
 report=json.loads((OUT/'build-report.json').read_text());d=report['design'];body=report['body']
 raw=(PCB_INPUT).read_bytes();assert hashlib.sha256(raw).hexdigest()==report['pcbSha256']
 rows=json.loads(raw);source={r['source_component_id']:r['name'] for r in rows if r['type']=='source_component'}
 pcbs={source[r['source_component_id']]:r for r in rows if r['type']=='pcb_component' and r.get('source_component_id') in source}
 bounds=json.loads((REFERENCE/'current-bounds.json').read_text())
 solids={n:evaluate(json.loads((OUT/f'{n}.jscad.json').read_text())) for n in report['parts']}
 checks=[]
 def check(name,vol,limit=.005):checks.append({'check':name,'intersectionMm3':round(float(vol),6),'pass':float(vol)<limit})
 def condition(name,passed,**details):checks.append({'check':name,'pass':bool(passed),**details})
 def metric(name,value,minimum):checks.append({'check':name,'valueMm':round(float(value),4),'minimumMm':minimum,'pass':float(value)>=minimum-1e-9})
 k=d['knob'];measured=json.loads((REFERENCE/'controls-measurements.json').read_text())['RV1']
 shaft_top=measured['max'][2]
 # Shaft height from the Alps LM1 (mounting surface to shaft end); the EasyEDA
 # 3D model of C361173 is shorter, so its measurement is recorded, not trusted.
 condition('SPEED shaft tip from Alps LM1 (PCB top 0.8 + LM1)',abs(.8+k['lm1']-k['shaftTop'])<1e-6,designMm=k['shaftTop'],easyedaModelTipMm=shaft_top)
 tabs=[r for r in json.loads((PCB_INPUT).read_text()) if r['type']=='pcb_plated_hole' and abs(r['y']-k['y'])<.01 and abs(r['x']-k['x'])<5]
 condition('SPEED shaft axis on the RK09 mounting-tab line',len(tabs)==2 and abs((tabs[0]['x']+tabs[1]['x'])/2-k['x'])<.05,tabXs=[t['x'] for t in tabs])
 shaft=(cyl(k['x'],k['y'],8.9,k['shaftTop'],k['shaftRadius'])-box([k['x']-4,k['y']-4,k['flatBottom']],[k['x']+4,k['y']-k['shaftFlat'],k['shaftTop']+1]))
 b=next(r for r in rows if r['type']=='pcb_board');x,y=b['center'].values();half=b['thickness']/2
 pcb=box([x-b['width']/2,y-b['height']/2,-half],[x+b['width']/2,y+b['height']/2,half])
 for h in [r for r in rows if r['type']=='pcb_hole']:pcb-=cyl(h['x'],h['y'],-2,2,h['hole_diameter']/2)
 for name in ['base','lid']:check(name+' / PCB', (solids[name]^pcb).volume())
 check('base / lid',(solids['base']^solids['lid']).volume())
 for lift in [.15,1,3,6,12,25]:
  check(f'lid assembly path {lift} / base',(solids['lid'].translate([0,0,lift])^solids['base']).volume())
  check(f'lid assembly path {lift} / PCB',(solids['lid'].translate([0,0,lift])^pcb).volume())
 envelopes={};fallback=[]
 for name,p in pcbs.items():
  if name.startswith('TP'):continue
  if name=='RV1':
   a=bounds[name];env=box([a['min'][0]-.35,a['min'][1]-.35,.45],[a['max'][0]+.35,a['max'][1]+.35,8.85])+cyl(k['x'],k['y'],8.3,k['shaftTop']+.35,k['shaftRadius']+.35)
  elif name=='SW4':
   # SK-22D03-G080: 8.38 x 6.86 x 4.7 mm body at the PCB edge; 8 mm lever swept over its full travel.
   pw=d['power'];hs=pw['leverWidth']/2+pw['travel']/2
   env=box([pw['bodyFaceX']-.35,pw['y']-4.19-.35,.45],[pw['bodyBackX']+.35,pw['y']+4.19+.35,5.5+.35])
   env+=box([pw['leverTipX']-.15,pw['y']-hs-.15,pw['leverBottom']-.15],[pw['bodyFaceX']+.1,pw['y']+hs+.15,pw['leverTop']+.15])
  elif name in ['C93','C94','C95','C96']:
   env=cyl(p['center']['x'],p['center']['y'],.45,15.3,5.6)
  elif name=='C191':
   # GVL0J332M1213 nominal height is 13.5 mm. Retain the larger prior
   # 13.8 mm base / 14.5 mm height envelope plus 0.15 mm clearance.
   # This is a conservative design allowance, not a supplier tolerance claim.
   x,y=p['center'].values();env=box([x-7.05,y-7.05,.45],[x+7.05,y+7.05,.8+14.5+.15])
  elif name=='BZ1':env=cyl(p['center']['x'],p['center']['y'],.45,7.3,5)
  elif name in bounds and max(np.array(bounds[name]['max'])-bounds[name]['min'])>.001:
   lo=np.array(bounds[name]['min'])-.35;hi=np.array(bounds[name]['max'])+.35
   if name in ['J10','J11','J12']:lo[2]=.45
   env=box(lo,hi)
  else:
   fallback.append(name);c=p['center'];h=4.5 if name=='F1' else 3.5
   env=box([c['x']-p['width']/2-.35,c['y']-p['height']/2-.35,.45],[c['x']+p['width']/2+.35,c['y']+p['height']/2+.35,h])
  if name in ['RV1','J10','J11','J12']:
   for h in rows:
    if h['type']=='pcb_plated_hole' and h.get('pcb_component_id')==p['pcb_component_id']:
     pos=h.get('center',h);env+=cyl(pos['x'],pos['y'],bounds[name]['min'][2]-.35,-.45,h.get('hole_diameter',h.get('hole_width',1))/2+.35)
  envelopes[name]=env
  for case in ['base','lid']:check(f'{case} / {name} clearance',(solids[case]^env).volume())
  for lift in [1,3,6,12,25]:check(f'lid assembly path {lift} / {name}',(solids['lid'].translate([0,0,lift])^env).volume())
 # New display is mechanically supported by a removable lid carrier.
 h=d['screen'];holder=solids['screen-holder'];door=solids['screen-door'];D=d['door']
 check('Screen holder / lid',(holder^solids['lid']).volume())
 check('Screen holder / PCB',(holder^pcb).volume())
 # The display seat, window and retainer inserts are in the removable screen door.
 check('Screen door / lid',(door^solids['lid']).volume())
 check('Screen door / screen holder',(door^holder).volume())
 check('Screen door / PCB',(door^pcb).volume())
 check('Screen door / base',(door^solids['base']).volume())
 panel=box([h['x']-h['panelWidth']/2-.1,h['panelY']-h['panelDepth']/2-.1,h['panelBottom']-.1],
           [h['x']+h['panelWidth']/2+.1,h['panelY']+h['panelDepth']/2+.1,h['glassTop']+.1])
 for part in ['base','lid','screen-holder','screen-door']:check('OLED glass clearance / '+part,(panel^solids[part]).volume())
 for name,env in envelopes.items():
  check('OLED glass / '+name,(panel^env).volume())
  check('Screen holder / '+name,(holder.translate([0,0,-.15])^env).volume())
  check('Screen door / '+name,(door^env).volume())
 for x,y in h['screws']:
  tip=h['screwSeat']+h['screwLength']
  hw=cyl(x,y,h['screwSeat'],tip,1)+cyl(x,y,h['screwSeat']-h['screwHeadHeight'],h['screwSeat'],2)
  for part in ['lid','screen-door','screen-holder']:check('OLED holder screw / '+part,(hw^solids[part]).volume())
  check('OLED holder screw / glass',(hw^panel).volume())
  for name,env in envelopes.items():check('OLED holder screw / '+name,(hw^env).volume())
  # Retainer is assembled into the screen door on the bench, away from the case.
  tool=cyl(x,y,-5,h['screwSeat']-h['screwHeadHeight'],2)
  check('OLED underside screwdriver access, door on the bench',(tool^(door+holder)).volume())
 condition('OLED holder insert engagement',min(tip,h['insertTop'])-h['insertBottom']>=2.0-1e-6)
 condition('OLED holder screw blind-hole margin',h['insertTop']+.1-tip>=.5-1e-6)
 condition('OLED blind insert roof thickness',d['top']-(h['insertTop']+.1)>=.6-1e-6)
 condition('OLED rear frame body thickness',abs(h['holderTop']-h['holderBottom']-1.5)<1e-6)
 condition('OLED shallow 0.8 mm recess',abs(d['top']-h['glassTop']-.8)<1e-6)
 condition('OLED stock ribbon length preserved',h['tailLength']==36)
 condition('OLED perimeter pads outside active pixels',h['adhesiveX']-h['adhesiveWidth']/2>h['activeWidth']/2)
 condition('OLED pads fit inactive glass edge',h['adhesiveX']+h['adhesiveWidth']/2<h['panelWidth']/2)
 condition('OLED pads lie fully on glass',h['y']-h['adhesiveLength']/2>h['panelY']-h['panelDepth']/2 and h['y']+h['adhesiveLength']/2<h['panelY']+h['panelDepth']/2)
 condition('OLED stock ribbon straight inserted stiffener',h['stiffenerLength']>h['insertion'])
 condition('OLED front pad thickness',abs(h['seatBottom']-h['glassTop']-h['padThickness'])<1e-6)
 condition('OLED rear pad thickness',abs(h['panelBottom']-h['holderTop']-h['padThickness'])<1e-6)
 for sign in (-1,1):
  xx=h['x']+sign*h['adhesiveX']
  for label,solid,z0 in [('front ledge',door,h['seatBottom']),('rear frame',holder,h['holderTop']-.01)]:
   probe=box([xx-h['adhesiveWidth']/2,h['y']-h['adhesiveLength']/2,z0],[xx+h['adhesiveWidth']/2,h['y']+h['adhesiveLength']/2,z0+.01])
   area=(probe^solid).volume()/.01
   condition(f'OLED strip {sign} / {label} contact',area>=h['adhesiveWidth']*h['adhesiveLength']*.99,areaMm2=area)
 # Check closed window walls at intermediate depths, including the old slit location.
 for sign in (-1,1):
  for fraction in (.25,.5,.75):
   z=h['glassTop']+.1+(d['top']-h['glassTop']-.1)*fraction
   yy=h['panelY']+sign*(h['locatingDepth']/2+.2)
   probe=box([h['x']-8,yy-.05,z],[h['x']+8,yy+.05,z+.01])
   condition(f'OLED continuous window wall {sign}/{fraction}',(probe^door).volume()/probe.volume()>.99)

 # A zero-thickness face can block pixels yet have zero intersection volume.
 # Cast vertical rays through the exported STL, independently of solid checks.
 for part in ['lid','screen-door','screen-holder']:
  triangles=trimesh.load_mesh(OUT/f'{part}-assembled.stl').triangles
  a,b,c=triangles[:,0,:2],triangles[:,1,:2],triangles[:,2,:2]
  den=(b[:,1]-c[:,1])*(a[:,0]-c[:,0])+(c[:,0]-b[:,0])*(a[:,1]-c[:,1])
  valid=np.abs(den)>1e-9;den=np.where(valid,den,1)
  for dx in [-h['activeWidth']/2+.05,0,h['activeWidth']/2-.05]:
   for dy in [-h['activeHeight']/2+.05,0,h['activeHeight']/2-.05]:
    x,y=h['x']+dx,h['y']+dy
    wa=((b[:,1]-c[:,1])*(x-c[:,0])+(c[:,0]-b[:,0])*(y-c[:,1]))/den
    wb=((c[:,1]-a[:,1])*(x-c[:,0])+(a[:,0]-c[:,0])*(y-c[:,1]))/den;wc=1-wa-wb
    z=wa*triangles[:,0,2]+wb*triangles[:,1,2]+wc*triangles[:,2,2]
    blocked=valid&(wa>=-1e-7)&(wb>=-1e-7)&(wc>=-1e-7)&(z>h['glassTop']+.01)
    condition(f'OLED exported STL sight line / {part} at {dx},{dy}',not blocked.any())
 # Check the exported connector datum, not just its electrical footprint.
 # An inferred body-center origin previously shifted its CAD by 2.7 mm.
 j21=pcbs['J21'];origin=j21['footprint_origin']
 cad=next(r for r in rows if r['type']=='cad_component' and r.get('pcb_component_id')==j21['pcb_component_id'])
 condition('OLED connector has explicit pin-row CAD origin',cad.get('model_origin_position')=={'x':0,'y':0,'z':0})
 condition('OLED connector mouth matches drawing',abs(bounds['J21']['min'][1]-(origin['y']-2))<.005)
 if LAYOUT:
  mechanical=json.loads((OUT/'mechanical.circuit.json').read_text())
  sc=next(r for r in mechanical if r['type']=='source_component' and r.get('name')=='OLED_FLEX')
  flex=evaluate(next(r['model_jscad'] for r in mechanical if r['type']=='cad_component' and r.get('source_component_id')==sc['source_component_id']))
 else: flex=evaluate(json.loads((ROOT/'../assembly/dist/assets/accessory-OLED_FLEX.jscad.json').read_text()))
 for part in ['base','lid','screen-holder','screen-door']:
  check('OLED ribbon / '+part,(flex^solids[part]).volume())
 check('OLED ribbon / PCB',(flex^pcb).volume())
 # Use the actual connector mesh. Metal contact springs intentionally touch
 # the ribbon; they are excluded from a plastic-obstruction test only.
 # CAD is nominal: this does not establish ribbon-width tolerance or retention.
 connector_scene=trimesh.load(ROOT/'reference-models/molex5034802400.obj',force='scene',process=True)
 # The supplier OBJ has non-watertight plastic meshes. Test each triangle
 # against the nominal stiffener box with separating axes; do not repair or
 # silently skip those surfaces. Contact-spring metal is intentionally excluded.
 def triangle_box_overlap(tri,lo,hi):
  center=(lo+hi)/2;extent=(hi-lo)/2;t=tri-center
  edges=[t[1]-t[0],t[2]-t[1],t[0]-t[2]]
  axes=[np.eye(3)[i] for i in range(3)]+[np.cross(edges[0],edges[1])]
  axes += [np.cross(edge,axis) for edge in edges for axis in np.eye(3)]
  for axis in axes:
   if np.linalg.norm(axis)<1e-10:continue
   proj=t@axis;r=extent@np.abs(axis)
   if proj.min()>r+1e-8 or proj.max()<-r-1e-8:return False
  return True
 tip=-2+h['insertion'];lo=np.array([-6.25,tip-h['stiffenerLength'],.4]);hi=np.array([6.25,tip,.7])
 plastic_hits=[]
 for i,(name,m) in enumerate(connector_scene.geometry.items()):
  if i not in (0,1,4):continue
  for index,tri in enumerate(m.triangles):
   if triangle_box_overlap(tri,lo,hi):plastic_hits.append([i,index])
 condition('OLED nominal stiffener / connector plastic surfaces',not plastic_hits,intersectingTriangles=plastic_hits[:10])
 condition('OLED nominal insertion follows Molex drawing',abs(h['insertion']-1.58)<1e-6)
 for name,env in envelopes.items():
  if name!='J21':check('OLED ribbon / '+name,(flex^env).volume())
 # The lid is closed first. The door, with glass and retainer fitted, then drops straight
 # through the opening: check that path against the lid and every component envelope.
 group=door+holder+panel
 for lift in [.15,1,3,6,12,25]:
  check(f'screen door installation path {lift} / lid',(group.translate([0,0,lift])^solids['lid']).volume())
  for name,env in envelopes.items():check(f'screen door installation path {lift} / {name}',(group.translate([0,0,lift])^env).volume())
 condition('Screen door cannot pass through its seat',(door.translate([0,0,-.3])^solids['lid']).volume()>1)
 # Two M2 x 4 screws from the top into M2 x 3 inserts in the lid (retainer hardware).
 for x,y in D['screws']:
  tip=d['top']-D['screwLength']
  hw=cyl(x,y,tip,d['top'],1)+cyl(x,y,d['top'],d['top']+D['screwHeadHeight'],D['screwHeadRadius'])
  for part in ['lid','screen-door','screen-holder','speed-knob']:check(f'Door screw {x},{y} / '+part,(hw^solids[part]).volume())
  for name,env in envelopes.items():check(f'Door screw {x},{y} / '+name,(hw^env).volume())
  tool=cyl(x,y,d['top']+D['screwHeadHeight'],d['top']+40,2)
  check(f'Door screwdriver access {x},{y}',(tool^(solids['lid']+door+solids['speed-knob'])).volume())
  condition(f'Door screw {x},{y} insert engagement',D['insertTop']-tip>=2.0-1e-6,engagementMm=D['insertTop']-tip)
  condition(f'Door screw {x},{y} blind-hole margin',tip-D['holeBottom']>=.5-1e-6,marginMm=tip-D['holeBottom'])
  check(f'Door insert boss {x},{y} is continuous lid plastic',(cyl(x,y,D['bossBottom']+.05,D['holeBottom']-.05,D['bossRadius']-.1)-solids['lid']).volume())
  check(f'Door insert hole {x},{y} is open from above',(cyl(x,y,D['holeBottom']+.05,D['insertTop'],1.6)^solids['lid']).volume())
 condition('Door screw tab rests on a 1 mm lid step',abs(d['roofBottom']+D['bevel']-(d['top']-D['tabThickness']))<1e-6)
 # The flex leaves between the glass sheets: nothing may face the glass edge there.
 edge=h['panelY']-h['panelDepth']/2
 relief=box([h['x']-6,edge-2,d['roofBottom']+.05],[h['x']+6,edge-.05,h['seatBottom']-.05])
 check('OLED flex has 2 mm free space ahead of the glass edge',(relief^(solids['lid']+door)).volume())
 pin=d['pinhole'];bb=d['button'];wire=pin['wireDiameter']/2
 for q in report['buttons']:
  if q['ref'] not in report['pinholeRefs']:continue
  # BOOT and RESET have no cap: a straightened paperclip reaches the switch through a guided pinhole.
  x,y=q['x'],q['y'];stem=cyl(x,y,bb['switchBodyTop'],bb['switchTop'],bb['plungerRadius'])
  check(q['ref']+' pinhole / paperclip path from above the lid to the switch',(cyl(x,y,bb['switchTop']-.5,d['top']+5,wire)^solids['lid']).volume())
  check(q['ref']+' pinhole guide / KH plunger at rest',(solids['lid']^stem).volume())
  check(q['ref']+' pinhole guide / KH plunger with the lid seated 0.15 mm lower',(solids['lid'].translate([0,0,-.15])^stem).volume())
  condition(q['ref']+' pinhole guide ends at least 0.5 mm above the plunger',pin['guideBottom']-.15-bb['switchTop']>=.5,clearanceMm=pin['guideBottom']-.15-bb['switchTop'])
  # Worst case: the wire leans as far as the hole allows and the plunger is fully pressed (0.25 mm).
  lean=(2*pin['radius']-pin['wireDiameter'])/(d['top']-pin['guideBottom'])
  reach=pin['radius']-wire+lean*(pin['guideBottom']-(bb['switchTop']-.25))+wire
  condition(q['ref']+' paperclip stays on the plunger at any angle the hole allows',bb['plungerRadius']-reach>=.3,marginMm=bb['plungerRadius']-reach)
  condition(q['ref']+' pinhole takes a 0.9 mm paperclip and refuses a 3 mm fingertip probe',pin['wireDiameter']+.6<=2*pin['radius']<=2.4 and 2*pin['leadInRadius']<=3.0,holeMm=2*pin['radius'],leadInMm=2*pin['leadInRadius'])
  condition(q['ref']+' pinhole guide wall is at least 1.6 mm',pin['guideRadius']-pin['radius']>=1.6,wallMm=pin['guideRadius']-pin['radius'])
  for name,env in envelopes.items():
   if name!=q['ref']:check(f'{q["ref"]} pinhole guide / {name}',(cyl(x,y,pin['guideBottom'],d['roofBottom'],pin['guideRadius'])^env).volume())
 for q in report['buttons']:
  if q['ref'] in report['pinholeRefs']:continue
  plunger=solids['button-plunger'].translate([q['x'],q['y'],0])
  for z in [0,-.5,.5]:
   moving=plunger.translate([0,0,z]);check(f'{q["ref"]} stroke {z} / lid',(moving^solids['lid']).volume())
   for name,env in envelopes.items():
    if name!=q['ref']:check(f'{q["ref"]} stroke {z} / {name}',(moving^env).volume())
  plunger=cyl(q['x'],q['y'],bb['switchBodyTop'],bb['switchTop'],bb['plungerRadius'])
  check(q['ref']+' cap / KH plunger at rest',(solids['button-plunger'].translate([q['x'],q['y'],0])^plunger).volume())
  condition(q['ref']+' cap socket clears the plunger radially',bb['socketRadius']-bb['plungerRadius']>=.15,clearanceMm=bb['socketRadius']-bb['plungerRadius'])
  condition(q['ref']+' cap socket engages the plunger',bb['switchTop']-bb['tipBottom']>=2.5,depthMm=bb['switchTop']-bb['tipBottom'])
  condition(q['ref']+' cap skirt clears the switch body when pressed',bb['tipBottom']-.25-bb['switchBodyTop']>=1.0,clearanceMm=bb['tipBottom']-.25-bb['switchBodyTop'])
  condition(q['ref']+' cap stays above lid when fully pressed',bb['top']-.25-d['top']>=.4,projectionMm=bb['top']-.25-d['top'])
  condition(q['ref']+' flange has lift room under the roof',d['roofBottom']-bb['flangeTop']>=.3,liftMm=d['roofBottom']-bb['flangeTop'])
  condition(q['ref']+' flange retained by roof',d['button']['flangeRadius']>d['button']['boreRadius'])
 for h in report['mountingHoles']:
  hw=cyl(h['x'],h['y'],.8-d['pcbMount']['screwLength'],.8,1.5)+cyl(h['x'],h['y'],.8,3.8,2.8)
  for name,env in envelopes.items():check(f'PCB screw {h["pcb_hole_id"]} / {name}',(hw^env).volume())
  check('PCB screw / lid',(hw^solids['lid']).volume())
  check('PCB screw / base',(hw^solids['base']).volume())
 for port in report['portOpenings']:
  a=box([port['x']-port['width']/2,port['y']-port['depth']/2,port['bottom']],[port['x']+port['width']/2,port['y']+port['depth']/2,port['top']])
  check(port['name']+' opening',(a^(solids['base']+solids['lid'])).volume())
 # M2 case bolts are inserted upwards from the underside. Include blind-hole
 # depth, real shank length and a driver access envelope, not only screw axes.
 for x,y in d['caseBolts']:
  f=d['flange'];tip=f['headSeat']+f['screwLength']
  hw=cyl(x,y,f['headSeat']-1.3,f['headSeat'],1.95)+cyl(x,y,f['headSeat'],tip,1.0)
  for case in ['base','lid']:check(f'case bolt {x},{y} / {case}',(hw^solids[case]).volume())
  check(f'case bolt {x},{y} / PCB',(hw^pcb).volume())
  for name,env in envelopes.items():check(f'case bolt {x},{y} / {name}',(hw^env).volume())
  tool=cyl(x,y,-30,f['headSeat'],1.95)
  check(f'case driver access {x},{y}',(tool^(solids['base']+solids['lid'])).volume())
  condition(f'case bolt {x},{y} insert engagement',tip-f['bottom']>=2.5,engagementMm=tip-f['bottom'])
  condition(f'case bolt {x},{y} blind-hole margin',f['bottom']+3.6-tip>=.5,marginMm=f['bottom']+3.6-tip)
 condition('PCB screw blind-hole margin',.8-d['pcbMount']['screwLength']-d['pcbMount']['holeBottom']>=.4)
 condition('PCB mount blind-hole floor thickness',d['pcbMount']['holeBottom']-d['bottom']>=1.2,thicknessMm=d['pcbMount']['holeBottom']-d['bottom'])
 condition('PCB insert remains above the blind-hole end',d['pcbMount']['insertTop']-d['inserts']['m3']['length']-d['pcbMount']['holeBottom']>=.5,marginMm=d['pcbMount']['insertTop']-d['inserts']['m3']['length']-d['pcbMount']['holeBottom'])
 # Check the actual native hole centres against the floor, including 1.5 mm
 # air underneath the allowance-expanded leads; no lead trimming is assumed.
 for name in ['J10','J11','J12','RV1']:
  lowest=bounds[name]['min'][2]-.35
  pins=[h for h in rows if h['type']=='pcb_plated_hole' and h.get('pcb_component_id')==pcbs[name]['pcb_component_id']]
  for i,h in enumerate(pins):
   pos=h.get('center',h)
   clearance=cyl(pos['x'],pos['y'],lowest-1.5,lowest,h.get('hole_diameter',h.get('hole_width',1))/2+.35)
   check(f'{name} lead {i} / 1.5 mm air to base',(clearance^solids['base']).volume())
 lowest_lead=min(bounds[n]['min'][2]-.35 for n in ['J10','J11','J12','RV1'])
 condition('Through-hole lead to base floor clearance',lowest_lead-d['floorTop']>=1.5,clearanceMm=lowest_lead-d['floorTop'])
 condition('Original PCB inserts and screws retained',d['inserts']['m3']['length']==5.7 and d['inserts']['m3']['diameter']==4.6 and d['inserts']['m3']['holeDiameter']==4.2 and d['pcbMount']['screwLength']==8)
 metric('PCB original insert screw engagement',min(d['inserts']['m3']['length'],d['pcbMount']['insertTop']-(.8-d['pcbMount']['screwLength'])),5.7)
 for h in report['mountingHoles']:
  bottom=cyl(h['x'],h['y'],d['bottom']+.01,d['pcbMount']['holeBottom']-.01,d['inserts']['m3']['holeDiameter']/2-.01)
  check('Original insert blind bore has continuous plastic below it',(bottom-solids['base']).volume())
 floor_land=box([-51,12,d['bottom']+.01],[-47,16,d['floorTop']-.01])
 check('Original base floor is solid down to flat underside',(floor_land-solids['base']).volume())
 condition('Original PCB support height restored',abs(-report['board']['thickness']/2-d['floorTop']-5.8)<1e-8)
 condition('Original overall case height retained',abs(d['top']-d['bottom']-28.6)<1e-8)
 # Side-facing PH plug: continuous horizontal insertion/removal envelope, 0.3 mm clearance.
 ph=box([27.5,28.15,1.47],[55,40.65,6.57])
 check('J20 horizontal plug insertion path / case',(ph^(solids['lid']+solids['base'])).volume())
 # Two 8 mm access probes approach the housing's SIDES.
 # This closes the former top/bottom access void without moving the header.
 # These are access envelopes, not proof of fingertip comfort or retention force.
 e=d['encoder']
 plug=box([27.815,28.5,1.77],[34.665,40.3,6.27])
 for yy in e['fingerY']:
  finger=mf.Manifold.cylinder(25,e['fingerRadius'],circular_segments=48).rotate([0,90,0]).translate([34,yy,e['fingerZ']])
  check(f'J20 side pinch access at y {yy}',(finger^(solids['lid']+solids['base']+pcb+plug)).volume())
  for name,env in envelopes.items():check(f'J20 side access {yy} / {name}',(finger^env).volume())
  # A wider 12 mm finger pad stays outside the case wall; the distal 8 mm
  # envelope reaches the housing end. CAD clearance is not an ergonomic test.
  pad=mf.Manifold.sphere(6,circular_segments=48).translate([46,yy,e['fingerZ']])
  check(f'J20 outside finger pad {yy} / case',(pad^(solids['lid']+solids['base'])).volume())
 # Continuous removal envelope spans the seated housing through full withdrawal.
 # Add 0.5 mm around housing/cable and check the opening independent of probes.
 withdrawal=box([34,28.0,1.27],[60,40.8,6.77])
 check('J20 removal envelope with 0.5 mm allowance',(withdrawal^(solids['lid']+solids['base'])).volume())
 metric('J20 housing top clearance',e['top']-6.27,.5)
 metric('J20 housing bottom clearance',1.77-e['bottom'],.5)
 # Housing travel envelope must clear both case halves. The wall underneath
 # closes the view into the solder-tail cavity rather than moving the PCB/floor.
 opening=box([body['x']+body['width']/2-d['wall']-.1,e['y']-e['depth']/2,e['bottom']+.01],
             [body['x']+body['width']/2+.1,e['y']+e['depth']/2,e['top']-.01])
 check('J20 reduced opening is clear',(opening^(solids['lid']+solids['base'])).volume())
 closed=box([body['x']+body['width']/2-d['wall']+.1,e['y']-e['depth']/2+e['tongueClearance']+.1,d['floorTop']+.1],
            [body['x']+body['width']/2-.1,e['y']+e['depth']/2-e['tongueClearance']-.1,e['bottom']-.1])
 check('J20 lower cavity closed by base tongue',(closed-solids['base']).volume())
 # The eight former cooling-slot sites must be continuous roof plastic.
 for xx in [-28+i*5 for i in range(8)]:
  closed_roof=box([xx-.8,-1,d['roofBottom']+.1],[xx+.8,11,d['top']-.1])
  check(f'Closed top at former cooling slot x {xx}',(closed_roof-solids['lid']).volume())
 # Verify the exported USB bodies, conservative swept envelopes and both-plug access.
 usb=verify_usb(OUT,solids,pcb,envelopes,check,condition,metric)
 for xx in [-3.0979,8.9021,20.9021]:check('Motor adapter / case',(box([xx-3.4,65,4.9],[xx+3.4,85,11.7])^(solids['lid']+solids['base'])).volume())
 # Push-on knob: D bore fits the shaft, grips enough flat, clears roof and window.
 knob=solids['speed-knob']
 # Tightened push-on fit: the D bore itself clears the largest Alps shaft (6.00 mm, 4.50 mm
 # across the flat); only the three crush ribs touch it, by 0.045-0.07 mm.
 import math as _m
 ribzone=None
 for deg in k['gripRibs']:
  a=_m.radians(deg);w=k['gripRibWidth']/2+.02
  z=box([k['gripRibRadius']-.05,-w,k['stemBottom']],[k['boreRadius']+.35,w,k['gripRibEnd']+.05]).rotate([0,0,deg]).translate([k['x'],k['y'],0])
  ribzone=z if ribzone is None else ribzone+z
 for label,R,F in [('max',3.0,1.5),('min',2.975,1.475)]:
  sh=(cyl(k['x'],k['y'],8.9,k['shaftTop'],R)-box([k['x']-4,k['y']-4,k['flatBottom']],[k['x']+4,k['y']-F,k['shaftTop']+1]))
  check(f'SPEED knob bore outside crush ribs / {label} D-shaft',((knob^sh)-ribzone).volume())
  check(f'SPEED knob crush ribs touch {label} D-shaft',0.0 if (knob^sh).volume()>1e-4 else 1.0)
 inner=cyl(k['x'],k['y'],8.9,k['shaftTop'],k['gripRibRadius']-.01)-box([k['x']-4,k['y']-4,8],[k['x']+4,k['y']-k['boreFlat']+.01,k['shaftTop']+1])
 check('SPEED knob crush rib tips stay outside r=gripRibRadius',(knob^inner).volume())
 interference=[round(R-k['gripRibRadius'],3) for R in (2.975,3.0)]
 condition('SPEED knob crush-rib interference 0.03-0.10 mm',all(.03<=i<=.10 for i in interference),interferenceMm=interference)
 gap=[round(k['boreRadius']-R,3) for R in (3.0,2.975)];flatgap=[round(k['boreFlat']-F,3) for F in (1.5,1.475)]
 condition('SPEED knob bore slide clearance 0.05-0.15 mm',all(.05<=g<=.15 for g in gap+flatgap),roundGapMm=gap,flatGapMm=flatgap)
 play=_m.degrees(_m.asin(k['boreFlat']/k['shaftRadius'])-_m.atan2(k['shaftFlat'],_m.sqrt(k['shaftRadius']**2-k['shaftFlat']**2)))
 condition('SPEED knob rotational play before the flats bear',play<=3,playDeg=round(play,2))
 condition('SPEED knob D-flat engagement',k['shaftTop']-max(k['flatBottom'],k['stemBottom'])>=6,engagementMm=k['shaftTop']-max(k['flatBottom'],k['stemBottom']))
 condition('SPEED knob stem radial clearance in roof opening',k['openingRadius']-k['stemRadius']>=.3,clearanceMm=k['openingRadius']-k['stemRadius'])
 condition('SPEED knob cap clears the roof',k['capBottom']-d['top']>=.4,clearanceMm=k['capBottom']-d['top'])
 web=(d['screen']['upperX']-d['screen']['upperWidth']/2)-(k['x']+k['capRadius'])
 condition('SPEED knob cap edge to display aperture',web>=.8,clearanceMm=web)
 for part in ['lid','base','screen-holder','screen-door']:check('SPEED knob / '+part,(knob^solids[part]).volume())
 for name,env in envelopes.items():
  if name!='RV1':check('SPEED knob / '+name,(knob^env).volume())
 for q in report['buttons']:
  if q['ref'] not in report['pinholeRefs']:check(f'SPEED knob / {q["ref"]} cap',(knob^solids['button-plunger'].translate([q['x'],q['y'],0])).volume())
 # Bare panel illuminated area from the manufacturer's mechanical drawing.
 sx=d['screen']['x'];sy=d['screen']['y'];sz=d['screen']['glassTop']
 active=[sx-d['screen']['activeWidth']/2,sy-d['screen']['activeHeight']/2,sx+d['screen']['activeWidth']/2,sy+d['screen']['activeHeight']/2]
 for part in ['lid','screen-door','screen-holder']:
  check('OLED active sightline / '+part,(box([active[0],active[1],sz],[active[2],active[3],30])^solids[part]).volume())
 check('STATUS LED sightline through recessed floor',(cyl(d['led']['x'],d['led']['y'],2,20,1.1)^solids['lid']).volume())
 condition('Capacitor overhead allowance',d['roofBottom']-15.3>=2,clearanceMm=d['roofBottom']-15.3)
 condition('Capacitor vent clearance with lid seated 0.15 mm lower',d['roofBottom']-.15-15.3>=2,clearanceMm=d['roofBottom']-.15-15.3)
 condition('Flat roof with nothing standing above it',abs(report['parts']['lid']['bounds'][1][2]-d['top'])<.00001 and 'raised' not in d)
 # Screen remains legible at least ±10° horizontally and ±15° vertically.
 # A conservative expanding rectangle contains every ray in that view cone.
 zz=np.linspace(sz,20.6,40)
 for z0,z1 in zip(zz[:-1],zz[1:]):
  dx=(z1-sz)*np.tan(np.deg2rad(10));dy=(z1-sz)*np.tan(np.deg2rad(15))
  for part in ['lid','screen-door','screen-holder']:
   check(f'OLED viewing cone / {part} at {z0:.2f}',(box([active[0]-dx,active[1]-dy,z0],[active[2]+dx,active[3]+dy,z1])^solids[part]).volume())
 power=verify_power_recess(solids,d,envelopes,pcb,checks,check,metric)
 mount=verify_mount_flanges(solids,d,body,report,check,condition,metric)
 failed=[c for c in checks if not c['pass']]
 result={'status':'PASS' if not failed else 'FAIL','checkCount':len(checks),'modeledComponents':len(envelopes),'fallbackEnvelopes':fallback,'failed':failed,'powerSwitch':power,'mountFlanges':mount,'usbAccess':usb,'checks':checks,'scope':'CAD geometry and explicit clearance envelopes. Print tolerances, control ergonomics, thermal performance and actual part variations require prototype checks.'}
 (OUT/'mechanical-verification.json').write_text(json.dumps(result,indent=2)+'\n')
 print(json.dumps({k:v for k,v in result.items() if k!='checks'},indent=2));return bool(failed)
if __name__=='__main__':raise SystemExit(main())