mohan-bee/pocket-mic-tx-assembly

Pocket-sized ESP32-S3 wireless microphone transmitter with digital MEMS mic, 2.4‑GHz antenna/RF matching, USB/QSPI flash, Li‑ion charging and buck-boost power management, status LED, control key, and protective clip-on enclosure.

Version
0.0.3
License
unset
Stars
0

Use with the tscircuit CLI

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

tsci clone mohan-bee/pocket-mic-tx-assembly  # download the package files into ./pocket-mic-tx-assembly
tsci add mohan-bee/pocket-mic-tx-assembly    # add it to your project as @tsci/mohan-bee.pocket-mic-tx-assembly

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.

source/generate.py

"""Parametric screwless C5 transmitter housing. All dimensions are in mm."""

import json
import struct
from pathlib import Path

import cadquery as cq

ROOT = Path(__file__).parent
MODELS = ROOT / "models"
MODELS.mkdir(exist_ok=True)
BODY_W, BODY_L, BODY_Y = 26.0, 48.0, -10.5
SEAM, FRONT, REAR, HUMP = .95, -2.95, 4.30, 7.0
MIC = (5.0013, -4.95)
KEY = (8.55, 7.25)
LOCK_Y = -19.85
PALETTE = {
    "front-tray": "#171F2B",
    "rear-lid": "#2A3645",
    "clip": "#3A4A5D",
    "key": "#4998D3",
    "keeper": "#4998D3",
    "acoustic-gasket": "#55687B",
    "battery-envelope": "#7793A9",
}


def box(width, length, z0, z1, x=0, y=0):
    return cq.Workplane("XY").box(width, length, z1-z0).translate((x, y, (z1+z0)/2))


def rounded(width, length, z0, z1, radius, x=0, y=0):
    return box(width, length, z0, z1, x, y).edges("|Z").fillet(radius)


def cylinder(radius, z0, z1, x, y):
    return cq.Workplane("XY").workplane(offset=z0).center(x, y).circle(radius).extrude(z1-z0)


def keeper_post(radius, x0, x1):
    return cq.Workplane("YZ", origin=(x0, LOCK_Y, SEAM)).circle(radius).extrude(x1-x0)


def keeper_seat(shell):
    return shell.cut(keeper_post(.855, 11.35, 13.20)).cut(keeper_post(1.48, 12.29, 13.20))


def prism_xz(points, y, width):
    return cq.Workplane("XZ", origin=(0, y+width/2, 0)).polyline(points).close().extrude(width)


def lid_hook(y, side):
    section = [
        (11.43, 1.80), (12.05, 1.80), (12.05, 2.20),
        (12.48, 2.20), (12.48, 2.35), (11.94, 3.06), (11.42, 3.06),
    ]
    stem = box(.68, 3.45, -1.4, 2.84, x=side*11.77, y=y)
    return stem.union(prism_xz([(side*x, z) for x, z in section], y, 1.10))


def spring_clip():
    # The tip rolls into a 0.93 mm throat for the garment hem.
    side = (
        cq.Workplane("YZ", origin=(-3.55, 0, 0))
        .moveTo(-18.55, 7.18).lineTo(-13.65, 7.18).lineTo(-13.65, 10.12)
        .threePointArc((-13.767157, 10.402843), (-14.05, 10.52))
        .lineTo(-15.50, 10.52)
        .bezier([(-19.30, 10.52), (-23.70, 9.07), (-26.00, 9.07)], includeCurrent=True)
        .bezier([(-27.70, 9.07), (-29.30, 10.25), (-30.87, 10.25)], includeCurrent=True)
        .threePointArc((-31.45, 9.67), (-30.87, 9.09))
        .bezier([(-29.97, 9.09), (-28.90, 7.93), (-27.80, 7.93)], includeCurrent=True)
        .lineTo(-25.30, 7.93)
        .bezier([(-22.50, 7.93), (-20.20, 9.03), (-19.25, 9.03)], includeCurrent=True)
        .threePointArc((-18.755025, 8.824975), (-18.55, 8.33))
        .close()
    )
    arm = side.extrude(7.10).faces(">X or <X").edges().fillet(.42)
    shoe = box(8.70, 4.88, 7.18, 8.33, y=-16.10)
    ear = box(.55, .56, 7.31, 8.05, x=-4.40, y=-17.79)
    return arm.union(shoe).union(ear)


def add_clip_rails(lid):
    for side in (-1, 1):
        lid = lid.union(box(1.10, 6.25, 6.77, 8.82, x=side*5.48, y=-15.70))
        lid = lid.union(box(1.55, 6.25, 8.52, 8.82, x=side*5.25, y=-15.70))
    # Offset the shoe 0.4 mm to +X before sliding it away from the stop.
    keeper = box(.65, .68, 7.25, 8.20, x=-4.80, y=-18.48)
    return lid.union(keeper).union(box(11.85, .70, 6.78, 8.82, y=-13.13))


def make_tray():
    tray = rounded(BODY_W, BODY_L, FRONT, SEAM, 4.0, y=BODY_Y).faces("<Z").edges().fillet(.32)
    tray = tray.cut(rounded(23.4, 45.4, -1.63, SEAM+.20, 1.50, y=BODY_Y))
    for side in (-1, 1):
        # LED/component face is opposite these underside rails.
        tray = tray.union(box(.92, 18.0, -1.76, -.80, x=side*11.23, y=-.2))
        tray = tray.union(box(3.67, 1.05, -1.80, SEAM, x=side*6.50, y=12.21))
        tray = tray.union(box(3.67, .80, -1.80, SEAM, x=side*6.50, y=-12.03))
        tray = tray.union(lid_hook(-25.35, side)).union(lid_hook(1.60, side))
    return keeper_seat(tray.cut(cylinder(1.73, -1.91, -.7, *MIC)).cut(
        cylinder(.72, FRONT-.1, -1.82, *MIC)
    ))


def make_lid():
    shell = rounded(BODY_W, BODY_L, SEAM, REAR, 4.0, y=BODY_Y).faces(">Z").edges().fillet(.32)
    hump = rounded(BODY_W-.01, 24.25, REAR-.32, HUMP, 4.0, y=-22.37).faces(">Z").edges().fillet(.55)
    hump = hump.intersect(rounded(BODY_W, BODY_L, REAR-.04, HUMP+.05, 4.0, y=BODY_Y))
    inner = rounded(23.4, 45.4, SEAM-.10, 3.04, 1.50, y=BODY_Y)
    battery_inner = rounded(22.7, 22.55, 2.70, 5.65, 2.4, y=-22.65)
    lid = shell.union(hump).cut(inner).cut(battery_inner)
    for side in (-1, 1):
        for y in (-25.35, 1.60):
            # A 1.60 mm slide aligns each undercut with its separate exit.
            lid = lid.cut(box(.91, 5.45, SEAM-.1, 3.24, x=side*11.755, y=y+.80))
            lid = lid.cut(box(1.20, 3.00, 2.07, 3.24, x=side*12.03, y=y+.80))
            lid = lid.cut(box(1.23, 1.45, SEAM-.1, 3.24, x=side*12.025, y=y+1.60))
        for y in (-6.9, 6.35):
            lid = lid.union(box(.60, 1.80, .82, 3.08, x=side*11.34, y=y))
    lid = lid.cut(rounded(10.55, 2.15, 2.8, REAR+.3, .50, x=4.50, y=-10.45))
    lid = lid.cut(cylinder(.80, 2.8, REAR+.3, 5.55, 10.16))
    lid = lid.cut(cylinder(.80, 2.8, REAR+.3, 7.50, 10.16))
    lid = lid.cut(cylinder(.90, 2.8, REAR+.3, 8.14, -4.13))
    # C_XP near the upper PCB edge needs a hidden clearance pocket while
    # the rear lid translates by 1.60 mm to disengage its locks.
    lid = lid.cut(rounded(1.65, 1.03, SEAM-.10, 1.57, .20, x=-1.65, y=12.08))
    lid = lid.cut(cylinder(1.51, 3.43, REAR+.3, *KEY))
    return keeper_seat(add_clip_rails(lid.cut(cylinder(1.99, 2.8, 3.44, *KEY))))


def write_glb(part, color, filename, *, smooth=False):
    """Write raw PCB-axis, mm-coordinate meshes for tscircuit."""
    tolerance, angle = (.043, .21) if smooth else (.053, .15)
    shape = part.val().copy(mesh=False) if smooth else part.val()
    vertices, triangles = shape.tessellate(tolerance, angle)
    face_normals = []
    vertex_normals = [cq.Vector() for _ in vertices] if smooth else []
    for i, j, k in triangles:
        normal = (vertices[j]-vertices[i]).cross(vertices[k]-vertices[i])
        if normal.Length < 1e-9:
            continue
        face_normals.append(((i, j, k), normal))
        if smooth:
            # CadQuery keeps separate tessellation vertices for each CAD face.
            for index in (i, j, k):
                vertex_normals[index] = vertex_normals[index] + normal

    positions = bytearray()
    normals = bytearray()
    pmin = [float("inf")] * 3
    pmax = [float("-inf")] * 3
    for indices, face_normal in face_normals:
        for index in indices:
            xyz = vertices[index].toTuple()
            normal = vertex_normals[index] if smooth else face_normal
            positions.extend(struct.pack("<fff", *xyz))
            normals.extend(struct.pack("<fff", *normal.normalized().toTuple()))
            pmin = [min(value, bound) for value, bound in zip(xyz, pmin)]
            pmax = [max(value, bound) for value, bound in zip(xyz, pmax)]
    total = len(positions)+len(normals)
    channels = [int(color[i:i+2], 16)/255 for i in (1, 3, 5)]
    linear = [((value+.055)/1.055)**2.4 if value > .04045 else value/12.92 for value in channels]
    gltf = {
        "asset": {"version": "2.0", "generator": "CadQuery tessellation"},
        "scene": 0, "scenes": [{"nodes": [0]}],
        "nodes": [{"mesh": 0}],
        "meshes": [{"primitives": [{"attributes": {"POSITION": 0, "NORMAL": 1}, "material": 0}]}],
        "materials": [{"pbrMetallicRoughness": {"baseColorFactor": [*linear, 1], "metallicFactor": .025, "roughnessFactor": .83}}],
        "buffers": [{"byteLength": total}],
        "bufferViews": [
            {"buffer": 0, "byteOffset": 0, "byteLength": len(positions), "target": 34962},
            {"buffer": 0, "byteOffset": len(positions), "byteLength": len(normals), "target": 34962},
        ],
        "accessors": [
            {"bufferView": 0, "componentType": 5126, "count": len(positions)//12,
             "type": "VEC3", "min": pmin, "max": pmax},
            {"bufferView": 1, "componentType": 5126, "count": len(normals)//12, "type": "VEC3"},
        ],
    }
    description = json.dumps(gltf, separators=(",", ":")).encode()
    description += b" " * (-len(description) % 4)
    filename.write_bytes(
        struct.pack("<4sII", b"glTF", 2, 28+len(description)+total)
        + struct.pack("<I4s", len(description), b"JSON") + description
        + struct.pack("<I4s", total, b"BIN\0") + positions + normals
    )


def clean_clip_stl(filename):
    # OCC can repeat a vertex at a fillet seam when writing single precision.
    data = filename.read_bytes()
    facets = (data[i:i+50] for i in range(84, len(data), 50))
    facets = [f for f in facets if len({f[12:24], f[24:36], f[36:48]}) == 3]
    filename.write_bytes(data[:80] + struct.pack("<I", len(facets)) + b"".join(facets))


def assemble():
    parts = {
        "front-tray": make_tray(),
        "rear-lid": make_lid(),
        "clip": spring_clip(),
        "key": cylinder(1.37, 2.65, 4.50, *KEY).union(cylinder(1.79, 2.73, 3.18, *KEY)),
        "keeper": keeper_post(.80, 11.47, 12.42).union(keeper_post(1.35, 12.30, 13.08)),
        "acoustic-gasket": cylinder(1.54, -1.88, -.80, *MIC).cut(cylinder(.59, -2.0, -.68, *MIC)),
        "battery-envelope": rounded(20.0, 18.0, -1.25, 4.55, 1.0, y=-22.90),
    }
    pcb = box(22.5, 23, -.80, .80)
    assembly = cq.Assembly(name="PocketMicTX-C5")
    for name, part in parts.items():
        assert part.val().isValid() and len(part.solids().vals()) == 1, f"Invalid or fragmented {name}"
        color = PALETTE[name]
        rgb = [int(color[i:i+2], 16)/255 for i in (1, 3, 5)]
        assembly.add(part, name=name, color=cq.Color(*rgb))
        cq.exporters.export(part, str(MODELS / f"{name}.step"))
        if name not in {"battery-envelope", "acoustic-gasket"}:
            stl = MODELS / f"{name}.stl"
            cq.exporters.export(part, str(stl), tolerance=.052, angularTolerance=.15)
            if name == "clip":
                clean_clip_stl(stl)
        write_glb(part, color, MODELS / f"{name}.glb", smooth=name == "clip")
    assembly.add(pcb, name="PCB-envelope", color=cq.Color(.11, .39, .31))
    assembly.save(str(MODELS / "tx-assembled.step"), exportType="STEP")
    for name, part in {**parts, "pcb-envelope": pcb}.items():
        bounds = part.val().copy(mesh=False).BoundingBox()
        print(f"{name:19} {bounds.xlen:5.2f} × {bounds.ylen:5.2f} × {bounds.zlen:5.2f}")
    checks = [
        ("front-tray", "rear-lid"), ("front-tray", "pcb"), ("rear-lid", "pcb"),
        ("front-tray", "battery-envelope"), ("rear-lid", "battery-envelope"),
        ("rear-lid", "clip"), ("rear-lid", "key"), ("front-tray", "acoustic-gasket"),
        ("front-tray", "keeper"), ("rear-lid", "keeper"),
    ]
    parts["pcb"] = pcb
    for a, b in checks:
        overlap = sum(obj.Volume() for obj in parts[a].intersect(parts[b]).solids().vals())
        print(f"{a} / {b} overlap={overlap:.6g} mm³")
        assert overlap < .0001, f"Unintended interference on {a} / {b}"
    for dx, dy, dz in [(0, -.4, 0), (0, -.8, 0), (0, -1.2, 0), (0, -1.6, 0),
                       (0, -1.6, .8), (0, -1.6, 2)]:
        sliding_lid = parts["rear-lid"].translate((dx, dy, dz))
        for name in ("front-tray", "pcb", "battery-envelope"):
            overlap = sum(obj.Volume() for obj in sliding_lid.intersect(parts[name]).solids().vals())
            assert overlap < .0001, f"Interference on opening trajectory with {name} at {(dx, dy, dz)}"
    print("Lid travel / tray, PCB and battery: six solved poses are clear.")


if __name__ == "__main__":
    assemble()