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/prune-dangling-routing.py

"""Trim native-reported unused tails, including chains exposed by trimming.
Exact signatures make the cleanup reproducible when importing the saved session.
"""
from pathlib import Path
import json,sys,math
from collections import deque
from shapely.geometry import Point,LineString
from shapely.ops import substring
from routing_model import BoardModel,LAYERS
root=Path(__file__).resolve().parents[1];half=sys.argv[1]
file=Path(sys.argv[2]) if len(sys.argv)>2 else root/f'outputs/{half}/keyboard.circuit.json'
m=BoardModel(file);path=root/f'src/routing/{half}.json';data=json.loads(path.read_text());original=data['paths'];active=dict(enumerate(original))
traces={t['pcb_trace_id']:t for t in m.bytype['pcb_trace']};queue=deque()
for error in m.json:
 if 'error' not in error['type'] or 'endpoint' not in error.get('message',''):continue
 trace=traces.get(error.get('pcb_trace_id'))
 if not trace:continue
 net=m.idnet[trace['source_trace_id']];endpoint=min([p for p in trace['route'] if p['route_type']=='wire'],key=lambda p:math.hypot(p['x']-error['center']['x'],p['y']-error['center']['y']))
 queue.append((net,endpoint['layer'],(endpoint['x'],endpoint['y'])))
changed=set();seen=set()
def wire(item):return all(p['route_type']=='wire' for p in item['route'])
def anchored(net,layer,point):
 if any(layer in p['layers'] and p['shape'].buffer(.001).covers(point) for p in m.netpads[net]):return True
 for item in active.values():
  if item['net']!=net:continue
  for p in item['route']:
   if p['route_type']!='via' or point.distance(Point(p['x'],p['y']))>.001:continue
   lo,hi=sorted([LAYERS.index(p['from_layer']),LAYERS.index(p['to_layer'])])
   if lo<=LAYERS.index(layer)<=hi:return True
 return False
def positions(g):
 if g.is_empty:return []
 if g.geom_type=='Point':return [(g.x,g.y)]
 if g.geom_type=='LineString':return [g.coords[0],g.coords[-1]]
 return [p for child in g.geoms for p in positions(child)] if hasattr(g,'geoms') else []
while queue:
 net,layer,xy=queue.popleft();key=(net,layer,round(xy[0],5),round(xy[1],5))
 if key in seen:continue
 seen.add(key);point=Point(xy)
 if anchored(net,layer,point):continue
 candidates=[(i,t) for i,t in active.items() if t['net']==net and wire(t) and t['route'][0]['layer']==layer and min(point.distance(Point(t['route'][k]['x'],t['route'][k]['y'])) for k in [0,-1])<.002]
 if len(candidates)!=1:continue
 index,item=candidates[0];route=item['route'];line=LineString([(p['x'],p['y']) for p in route]);reverse=point.distance(Point(line.coords[-1]))<point.distance(Point(line.coords[0]))
 if reverse:line=LineString(list(line.coords)[::-1])
 old_length=line.length;other_end=line.coords[-1];distances=[]
 def add(xy):
  p=Point(xy)
  if line.distance(p)<.001:
   d=line.project(p)
   if d>1e-5:distances.append(d)
 for other_index,other in active.items():
  if other_index==index or other['net']!=net:continue
  for a,b in zip(other['route'],other['route'][1:]):
   if a['route_type']==b['route_type']=='wire' and a['layer']==b['layer']==layer:
    segment=LineString([(a['x'],a['y']),(b['x'],b['y'])]);add((a['x'],a['y']));add((b['x'],b['y']))
    for q in positions(line.intersection(segment)):add(q)
  for p in other['route']:
   if p['route_type']!='via':continue
   lo,hi=sorted([LAYERS.index(p['from_layer']),LAYERS.index(p['to_layer'])])
   if lo<=LAYERS.index(layer)<=hi:add((p['x'],p['y']))
 for pad in m.netpads[net]:
  if layer in pad['layers']:add((pad['x'],pad['y']))
 d=min(distances,default=old_length);changed.add(index)
 if d>=old_length-1e-5:
  del active[index];queue.append((net,layer,other_end));remaining=0
 else:
  line=substring(line,d,old_length)
  if reverse:line=LineString(list(line.coords)[::-1])
  active[index]={**item,'route':[{'route_type':'wire','x':round(x,7),'y':round(y,7),'width':route[0]['width'],'layer':layer} for x,y in line.coords]};remaining=line.length
 print(half,net,'trimmed',round(old_length-remaining,4),'mm')
patch_path=root/f'src/routing/{half}-repairs.json';patch=json.loads(patch_path.read_text());patch.setdefault('removeRoutes',[])
for index in sorted(changed):
 item=original[index];r=item['route'];patch['removeRoutes'].append({'net':item['net'],'layer':r[0]['layer'],'points':[[p['x'],p['y']] for p in r]})
 # Replacements from an earlier cleanup must also be removed from the patch list.
 patch['paths']=[p for p in patch['paths'] if p!=item]
 if index in active:patch['paths'].append(active[index])
data['paths']=list(active.values());path.write_text(json.dumps(data,indent=2)+'\n');patch_path.write_text(json.dumps(patch,indent=2)+'\n')