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/prepare-cad-models.py

"""Prepare the attributed upstream CAD assets; not needed for normal/cloud builds.

Run after installing trimesh, fast-simplification, numpy and rtree in .venv.
The small committed catalog embeds the meshes so previews need no external host.
"""
from pathlib import Path
import base64, hashlib, json, subprocess, urllib.request, urllib.parse
import numpy as np
import trimesh

ROOT = Path(__file__).resolve().parents[1]
CACHE = ROOT / '.cache/model-research'
OUT = ROOT / 'src/models'
CACHE.mkdir(parents=True, exist_ok=True)
OUT.mkdir(parents=True, exist_ok=True)
KLP = '8e4b89b484cafe3bcaced6b459a4e29660991a40'
SHARP = '029079672132b775a24bccd19b4fac88c1fcdd0f'
sources = []
models = {}

def source(repo, revision, path, filename):
    url = f'https://raw.githubusercontent.com/{repo}/{revision}/{urllib.parse.quote(path)}'
    file = CACHE / filename
    if not file.exists():
        file.write_bytes(urllib.request.urlopen(url, timeout=90).read())
    sources.append({'repository': f'https://github.com/{repo}', 'revision': revision,
                    'path': path, 'url': url, 'sha256': hashlib.sha256(file.read_bytes()).hexdigest()})
    return file

def material(color, name):
    return trimesh.visual.material.PBRMaterial(name=name, baseColorFactor=color,
                                               metallicFactor=0, roughnessFactor=.72)

def embed(name, meshes):
    scene = trimesh.Scene()
    for i, mesh in enumerate(meshes):
        scene.add_geometry(mesh, node_name=f'{name}_{i}')
    raw = scene.export(file_type='glb')
    models[name] = {'glbUrl': 'data:model/gltf-binary;base64,' + base64.b64encode(raw).decode(),
                    'bounds': np.round(scene.bounds, 6).tolist(),
                    'triangles': sum(len(m.faces) for m in meshes)}

for kind in ['normal', 'homing', 'thumb']:
    suffix = {'normal': 'Normal', 'homing': 'Normal_Homing', 'thumb': 'Thumb'}[kind]
    file = source('braindefender/KLP-Lame-Keycaps', KLP,
                  f'STL/Choc Stem + Choc Size/Choc_Stem_Choc_Size_{suffix}.stl', f'keycap-{kind}.stl')
    original = trimesh.load_mesh(file)
    mesh = original.simplify_quadric_decimation(face_count=6000)
    assert mesh.is_volume and np.allclose(mesh.bounds, original.bounds, atol=.015)
    # Screen every upstream vertex against the reduced surface, including stems.
    _, distances, _ = trimesh.proximity.closest_point(mesh, original.vertices)
    error = float(distances.max())
    assert error < .055, (kind, error)
    for color, rgba in [('ivory', [235,238,235,255]), ('blue', [76,127,151,255])]:
        colored = mesh.copy()
        colored.visual = trimesh.visual.TextureVisuals(material=material(rgba, f'KLP {color}'))
        embed(f'keycap-{kind}-{color}', [colored])
    sources[-1].update(license='CC-BY-SA-4.0', author='Nikita Shirokov (braindefender)',
                       reducedTriangles=len(mesh.faces), maximumVertexSurfaceErrorMm=round(error, 6))

# Import only the raw panel's three optical/glass solids. No breakout board.
source('karnadii/sharp_memory_display_breakout', SHARP,
       'lib/3d/memory display v1.step', 'sharp-v1.step')
subprocess.run(['node', str(ROOT / 'scripts/triangulate-step.cjs'),
                str(CACHE / 'sharp-v1.step'), str(CACHE / 'sharp-v1.json')], check=True)
step = json.loads((CACHE / 'sharp-v1.json').read_text())
assert step['success'] and len(step['meshes']) == 5
glass = []
for i, data in enumerate(step['meshes'][:3]):
    vertices = np.array(data['attributes']['position']['array']).reshape((-1, 3))
    # Correct the community model's active-area datum to Sharp's 17.173 mm.
    if i == 0:
        vertices[:, 0] += .557
    elif i == 1:
        # Move the aperture's inner edges with the corrected active window.
        inner = np.isclose(vertices[:,0],22.0000003278255) | np.isclose(vertices[:,0],47.2800003278255)
        vertices[inner,0] += .557
    vertices = np.c_[vertices[:,1] - 18.6280003576279,
                     36.3700003278256 - vertices[:,0], vertices[:,2] + .515]
    mesh = trimesh.Trimesh(vertices=vertices,
                          faces=np.array(data['index']['array']).reshape((-1, 3)), process=True)
    colors = [[166,179,160,255], [30,33,31,255], [60,67,65,255]]
    mesh.visual = trimesh.visual.TextureVisuals(material=material(colors[i], 'Sharp glass / polarizer'))
    glass.append(mesh)
embed('sharp-panel', glass)
assert np.allclose(np.ptp(np.concatenate([m.vertices for m in glass]), axis=0), [14,32,.745])
sources[-1].update(license='CERN-OHL-P-2.0', author='karnadii',
                   changes='Raw panel only, portrait orientation, corrected active-area and aperture datum, display materials; no PCB included. Original 5.5 mm tip retained; finished thickness corrected to 0.30 mm and gently bent into the top connector.')

data = step['meshes'][3]
mesh = trimesh.Trimesh(vertices=np.array(data['attributes']['position']['array']).reshape((-1,3)),
                      faces=np.array(data['index']['array']).reshape((-1,3)), process=True)
mesh = mesh.slice_plane([52.3700003278256,0,0], [1,0,0], cap=True)
mesh.vertices, mesh.faces = trimesh.remesh.subdivide_to_size(mesh.vertices, mesh.faces, max_edge=.8)
vertices = mesh.vertices.copy()
vertices = np.c_[vertices[:,1]-18.6280003576279, 36.3700003278256-vertices[:,0], vertices[:,2]*(.13/.15)]

# Integrate the horizontal shortening of an inextensible flex centerline.
# Merely lowering Z at unchanged Y would stretch the real 13.63 mm tail.
bend_t = np.linspace(0,1,4097)
bend_sine = 1.035/5.2 * 6*bend_t*(1-bend_t)
bend_loss_rate = 1-np.sqrt(1-bend_sine*bend_sine)
bend_loss = np.r_[0,np.cumsum((bend_loss_rate[:-1]+bend_loss_rate[1:])/2 * 5.2/4096)]

def flex_z(points):
    points = points.copy()
    # Sharp LD-29Y03: bend only 0.8..6.0 mm from the glass edge.
    # This smooth 5.2 mm transition has nominal minimum radius >4.3 mm,
    # comfortably above the specified R0.45 minimum, and leaves the tip flat.
    t = np.clip((12.2-(points[:,1]+29))/(12.2-7.0),0,1)
    sine = 1.035/5.2*6*t*(1-t)
    normal_offset = points[:,2]+.065
    points[:,1] += np.interp(t,bend_t,bend_loss)-sine*normal_offset
    points[:,2] = .450-1.035*(3*t*t-2*t*t*t)+np.sqrt(1-sine*sine)*normal_offset
    return points

mesh.vertices = flex_z(vertices)
mesh.visual = trimesh.visual.TextureVisuals(material=material([177,108,29,255], 'Polyimide flex'))
flex = [mesh]
# Sharp's 0.30 mm finished tail includes its 0.13 mm flex, not 0.30 + 0.13.
stiffener = trimesh.creation.box(extents=[5.5,4.65,.17])
stiffener.apply_translation([0,1.695-29,.085])
stiffener.vertices = flex_z(stiffener.vertices)
stiffener.visual = trimesh.visual.TextureVisuals(material=material([48,54,52,255], 'FPC stiffener'))
flex.append(stiffener)
for i in range(10):
    contact = trimesh.creation.box(extents=[.35,3.5,.005])
    contact.apply_translation([(i-4.5)*.5,1.27-29,-.1325])
    contact.vertices = flex_z(contact.vertices)
    contact.visual = trimesh.visual.TextureVisuals(material=material([205,166,69,255], 'Gold FPC contact'))
    flex.append(contact)
embed('sharp-flex', flex)
models['sharp-flex']['bend'] = {'permittedRegionFromGlassMm':[.8,6.0],
    'minimumNominalRadiusMm':round(5.2**2/(6*1.035),6),
    'horizontalShorteningMm':round(float(bend_loss[-1]),6),
    'freeCenterlineLengthMm':13.63,'finishedTailWidthMm':5.5,'finishedTailThicknessMm':.3,
    'contactEngagement':'Nominal modeled insertion; verify the physical panel and receptacle'}
for repo, rev, name, target in [('braindefender/KLP-Lame-Keycaps', KLP, 'KLP-LICENSE', 'LICENSE-KLP-CC-BY-SA-4.0.txt'),
                                ('karnadii/sharp_memory_display_breakout', SHARP, 'sharp-LICENSE', 'LICENSE-Sharp-CERN-OHL-P-2.0.txt')]:
    license_file = source(repo, rev, 'LICENSE', name)
    (OUT / target).write_bytes(license_file.read_bytes())

(OUT / 'catalog.json').write_text(json.dumps(models, separators=(',', ':')) + '\n')
(OUT / 'sources.json').write_text(json.dumps({'sources': sources,
    'changes': 'Keycaps tessellated to 6000 triangles, recolored, no scaling. Embedded GLB vertices use millimeters.'}, indent=2) + '\n')
print('Embedded', len(models), 'attributed CAD assets:', (OUT / 'catalog.json').stat().st_size, 'bytes')