MustafaMulla29/wireless-mouse-pcb

A 3D-printed wireless mouse enclosure housing a 44×70 mm PCB with nRF52810 BLE control, optical sensor, USB-C LiPo charging/power circuitry, buttons, scroll encoder/wheel, and battery bay.

Version
1.0.18
License
unset
Stars
0

Use with the tscircuit CLI

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

tsci clone MustafaMulla29/wireless-mouse-pcb  # download the package files into ./wireless-mouse-pcb
tsci add MustafaMulla29/wireless-mouse-pcb    # add it to your project as @tsci/MustafaMulla29.wireless-mouse-pcb

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/build.tsx

// Builds the mouse enclosure: JSCAD plans, print STLs, clearance checks and the
// native tscircuit assembly. Run from the project root:  bun run enclosure:build
import { createHash } from "node:crypto"
import { mkdir, readFile, writeFile } from "node:fs/promises"
import modeling from "@jscad/modeling"
import { renderToJscadPlan } from "jscad-fiber/headless"
import { executeJscadOperations } from "jscad-planner"
import { body, board, cad, component, design, pcbBottom, pcbTop, power, roofOuter, sideButtons, thtParts } from "./dimensions"
import { poses, printableParts } from "./parts"

const { booleans, measurements, primitives, transforms, geometries } = modeling

/** Binary STL from a JSCAD geom3 (polygons fanned into triangles). */
function toStl(shape: any) {
  const tris: number[][][] = []
  for (const poly of geometries.geom3.toPolygons(shape))
    for (let i = 1; i < poly.vertices.length - 1; i++) tris.push([poly.vertices[0], poly.vertices[i], poly.vertices[i + 1]])
  const buf = Buffer.alloc(84 + tris.length * 50)
  buf.write("mouse enclosure", 0)
  buf.writeUInt32LE(tris.length, 80)
  tris.forEach(([a, b, c], t) => {
    const u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]
    const v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]
    const n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]
    const len = Math.hypot(...n) || 1
    const o = 84 + t * 50
    ;[...n.map((x) => x / len), ...a, ...b, ...c].forEach((x, i) => buf.writeFloatLE(x, o + i * 4))
  })
  return buf
}
process.chdir(import.meta.dir)
await mkdir("dist", { recursive: true })
await mkdir("print", { recursive: true })

// The reference board must be the one the enclosure was reviewed against.
const provenance = JSON.parse(await readFile("reference-board.provenance.json", "utf8"))
const pcbHash = createHash("sha256").update(await readFile(provenance.source)).digest("hex")
if (pcbHash !== provenance.sha256)
  throw new Error(`${provenance.source} changed: run \`bun enclosure/extract-reference.ts\` and review the enclosure`)

// ---------------------------------------------------------------- parts
const solids: Record<string, any> = {}
const report: any = { pcbSha256: pcbHash, body: {}, parts: {}, checks: {} }
for (const [name, { Part, quantity }] of Object.entries(printableParts)) {
  const plan = renderToJscadPlan(<Part />)
  let shape = executeJscadOperations(modeling as any, plan) as any
  if (Array.isArray(shape)) shape = booleans.union(...shape)
  const volume = measurements.measureVolume(shape)
  if (!(volume > 0)) throw new Error(`Empty part ${name}`)
  const bounds = measurements.measureBoundingBox(shape)
  await writeFile(`dist/${name}.jscad.json`, JSON.stringify(plan))
  // Print files: assembly orientation, dropped onto the bed (minimum Z = 0).
  const onBed = transforms.translate([0, 0, -bounds[0][2]], shape)
  await writeFile(`print/${name}.stl`, toStl(onBed))
  const pose = poses[name] ?? [0, 0, 0]
  solids[name] = transforms.translate(pose, shape)
  report.parts[name] = { quantity, volumeMm3: +volume.toFixed(1), bounds: bounds.map((p: number[]) => p.map((v) => +v.toFixed(2))) }
  console.log(`${name.padEnd(16)} ${volume.toFixed(0).padStart(7)} mm³`)
}

// ---------------------------------------------------------------- envelopes
// Conservative component envelopes (board coordinates, z = 0 at the PCB centre).
type Env = { name: string; x0: number; x1: number; y0: number; y1: number; z0: number; z1: number }
const envs: Env[] = []
const add = (name: string, cx: number, cy: number, w: number, h: number, z0: number, z1: number) =>
  envs.push({ name, x0: cx - w / 2, x1: cx + w / 2, y0: cy - h / 2, y1: cy + h / 2, z0, z1 })
const k = design.key
for (const ref of ["SW_LEFT", "SW_RIGHT"]) {
  const c = cad(ref)
  add(`${ref} body`, c.x, c.y, 5.8, 12.8, pcbTop, pcbTop + k.switchBody)
  add(`${ref} actuator`, c.x, c.y + k.actuatorOffsetY, 2, 2, pcbTop, pcbTop + k.actuatorHeight)
}
const enc = cad("ENC_WHEEL")
add("ENC_WHEEL", enc.x, enc.y, 2 * design.encoder.halfWidthX, 2 * design.encoder.halfDepthY, pcbTop, pcbTop + design.encoder.top)
const pw = cad("SW_POWER")
add("SW_POWER body", pw.x, pw.y, 8.8, 3.9, pcbTop, pcbTop + power.leverBodyTop)
add("SW_POWER lever (start)", power.leverX, pw.y, power.leverWidth, 1.5, pcbTop, pcbTop + power.leverTop)
add("J_USB", cad("J_USB").x, (-32.3 + -25.5) / 2, 8.94, 6.8, pcbTop - 0.94, pcbTop + 3.22)
const sen = cad("U_SENSOR")
add("U_SENSOR", sen.x, sen.y, 10.9, 16.2, pcbTop, pcbTop + 1.8)
for (const ref of ["SW_MIDDLE", "SW_DPI"]) add(ref, cad(ref).x, cad(ref).y, 4.8, 5, pcbTop, pcbTop + design.tactHeight)
for (const s of sideButtons) {
  const c = cad(s.ref)
  envs.push({ name: s.ref, x0: c.x - 2.75, x1: c.x + 1.75, y0: c.y - 3.2, y1: c.y + 3.2, z0: pcbTop, z1: pcbTop + 1.65 })
}
const rs = cad("SW_RESET")
envs.push({ name: "SW_RESET", x0: rs.x - 1.75, x1: rs.x + 2.75, y0: rs.y - 3.2, y1: rs.y + 3.2, z0: pcbTop, z1: pcbTop + 1.65 })
const jb = component("J_BAT_PROTECTED")
add("J_BAT_PROTECTED", jb.center.x, jb.center.y, jb.width, jb.height, pcbTop, pcbTop + 5.5)
const named = new Set(envs.map((e) => e.name.split(" ")[0]))
for (const r of (await import("./reference-board.json")).default as any[]) {
  if (r.type !== "source_component" || named.has(r.name) || r.name === "SW_POWER") continue
  const c = component(r.name)
  add(r.name, c.center.x, c.center.y, Math.max(c.width, 0.5), Math.max(c.height, 0.5), pcbTop, pcbTop + (r.name.startsWith("TP_") ? 0.1 : 1.6))
}
// EVQPUC02K switches are SMD; only their plastic locating pegs pass the board.
const smdWithPegs = new Set(["SW_RESET", "SW_SIDE1", "SW_SIDE2"])
const refRows = (await import("./reference-board.json")).default as any[]
for (const ref of thtParts) {
  const c = component(ref)
  if (!smdWithPegs.has(ref)) {
    add(`${ref} leads`, c.center.x, c.center.y, c.width, c.height, pcbBottom - 2.3, pcbBottom)
    continue
  }
  for (const h of refRows.filter((r) => r.type === "pcb_hole" && r.pcb_component_id === c.pcb_component_id))
    add(`${ref} peg`, h.x, h.y, h.hole_diameter, h.hole_diameter, pcbBottom - 1.5, pcbBottom)
}
const [cw, cd, ch] = design.battery.cell
add("battery cell", design.battery.x, design.battery.y, cw, cd, design.floorTop, design.floorTop + ch)

const envSolid = (e: Env) =>
  primitives.cuboid({ size: [e.x1 - e.x0, e.y1 - e.y0, e.z1 - e.z0], center: [(e.x0 + e.x1) / 2, (e.y0 + e.y1) / 2, (e.z0 + e.z1) / 2] })
const pcbSolid = primitives.roundedRectangle({ size: [board.width, board.height], roundRadius: 5 })
const pcb = transforms.translate([0, 0, pcbBottom], modeling.extrusions.extrudeLinear({ height: board.thickness }, pcbSolid))

const overlap = (a: any, b: any) => {
  const [a0, a1] = measurements.measureBoundingBox(a)
  const [b0, b1] = measurements.measureBoundingBox(b)
  for (let i = 0; i < 3; i++) if (a1[i] <= b0[i] || b1[i] <= a0[i]) return 0
  return measurements.measureVolume(booleans.intersect(a, b))
}
// Intended contacts: the wheel axle enters the encoder rotor; PCB screws pass the PCB.
const allowed = new Set(["scroll-wheel|ENC_WHEEL"])
const failures: string[] = []
const tol = 1e-3
for (const [name, solid] of Object.entries(solids)) {
  const v = overlap(solid, pcb)
  if (v > tol) failures.push(`${name} intersects the PCB (${v.toFixed(3)} mm³)`)
  for (const e of envs) {
    if (allowed.has(`${name}|${e.name}`)) continue
    const v2 = overlap(solid, envSolid(e))
    if (v2 > tol) failures.push(`${name} intersects ${e.name} (${v2.toFixed(3)} mm³)`)
  }
}
const names = Object.keys(solids)
for (let i = 0; i < names.length; i++)
  for (let j = i + 1; j < names.length; j++) {
    const v = overlap(solids[names[i]], solids[names[j]])
    if (v > tol) failures.push(`${names[i]} intersects ${names[j]} (${v.toFixed(3)} mm³)`)
  }

const baseBounds = measurements.measureBoundingBox(solids.base)
const lidBounds = measurements.measureBoundingBox(solids.lid)
report.body = {
  footprintMm: [+(2 * body.halfWidth).toFixed(1), +(body.rear - body.front).toFixed(1)],
  heightAboveSurfaceMm: +(lidBounds[1][2] - design.surface).toFixed(2),
  baseBottomAboveSurfaceMm: +(baseBounds[0][2] - design.surface).toFixed(2),
  pcbTopToSurfaceMm: +(pcbTop - design.surface).toFixed(2),
  wheelProudMm: +(roofOuterAtWheel() ).toFixed(2),
}
function roofOuterAtWheel() {
  const axisZ = pcbTop + design.encoder.axisHeight
  return axisZ + design.wheel.radius - roofOuter(enc.y)
}
report.checks = { envelopes: envs.length, partPairs: (names.length * (names.length - 1)) / 2, failures }

await writeFile("dist/build-report.json", JSON.stringify(report, null, 2) + "\n")

console.log(JSON.stringify(report.body))
console.log(`${envs.length} envelopes, ${report.checks.partPairs} part pairs checked`)
if (failures.length) {
  console.error(failures.join("\n"))
  process.exit(1)
}
console.log("All clearance checks passed. STLs in enclosure/print/")