main
John Lauer Fit the interferometer test stage to the released 1.3 head and J4 map ffcc3ce
"""Generate the bench prototype in millimetres with CadQuery 2.8."""
import argparse
import json
from pathlib import Path

import cadquery as cq

parser = argparse.ArgumentParser()
parser.add_argument("head_step", type=Path)
parser.add_argument("motor_step", type=Path)
parser.add_argument("mirror_step", type=Path)
parser.add_argument("--out", type=Path, default=Path(__file__).parent)
parser.add_argument("--throw", type=float, default=80, help="Lens exit to mirror, mm")
parser.add_argument("--beam-height", type=float, default=33)
parser.add_argument("--lens-od", type=float, default=17.8)
args = parser.parse_args()
args.out.mkdir(parents=True, exist_ok=True)

Z = args.beam_height
if Z < 31 or args.throw < 50 or args.lens_od >= 21:
    parser.error("Require beam height ≥31 mm, throw ≥50 mm and barrel OD <21 mm")
head_seat = 15.995
head_xy = [(x, y) for x in (-82, -18) for y in (-32, 32)]
floor = 6
lens_exit = 19
mirror_x = lens_exit + args.throw
pivot_y = -5
drive_y = pivot_y + 50


def box(x, y, z, depth, width, height):
    return cq.Solid.makeBox(depth, width, height, cq.Vector(x, y, z))


def hole(radius, length, x, y, z, direction=(0, 0, 1)):
    return cq.Solid.makeCylinder(radius, length, cq.Vector(x, y, z), cq.Vector(*direction))


def export_print(name, shape):
    if not shape.isValid() or len(shape.Solids()) != 1:
        raise ValueError(f"{name} must be a valid single solid")
    cq.exporters.export(shape, str(args.out / f"{name}.stl"), tolerance=0.05, angularTolerance=0.15)
    cq.exporters.export(shape, str(args.out / f"{name}.step"))


base = box(-98, -91, 0, mirror_x + 199, 185, floor)
for x in (-89, mirror_x + 92):
    for y in (-82, 74):
        base = base.cut(hole(1.65, floor, x, y, 0))
for x, y in [(8, -13), (8, 13), (mirror_x + 31, -9), (mirror_x + 31, 9)]:
    base = base.cut(hole(1.65, floor, x, y, 0))
for y in (29.5, 60.5):
    for x in (mirror_x + 48, mirror_x + 67):
        base = base.cut(hole(1.65, floor, x, y, 0))

# Two screw holes secure the independently adjustable positive stop.
for dy in (-5,5):
    base = base.cut(hole(1.65, floor, mirror_x, drive_y+dy, 0))

# The separate optical fixture is held at the same axis as the mirror.
# The adjustable saddle accepts the nominal Ø17.8 mm SM05L05 tube.
lens_block = box(4, -17, floor, 10, 34, Z - floor)
lens_block = lens_block.cut(hole(args.lens_od / 2 + 0.125, 10, 4, 0, Z, (1, 0, 0)))
optic_strap = box(4, -17, Z + 0.35, 10, 34, args.lens_od / 2 + 3)
optic_strap = optic_strap.cut(hole(args.lens_od / 2 + 0.125, 10, 4, 0, Z - 0.05, (1, 0, 0)))
for y in (-13, 13):
    lens_block = lens_block.cut(hole(1.65, Z - floor, 8, y, floor))
    optic_strap = optic_strap.cut(hole(1.65, args.lens_od / 2 + 3, 8, y, Z + 0.35))

# TO-56 seat behind the sliding barrel. Machine the stepped bore in
# aluminium and place the seat on the insulating printed riser.
diode_seat = box(-5, -9, Z - 9, 5, 18, 18)
diode_seat = diode_seat.cut(hole(2.85, 1.25, -5, 0, Z, (1, 0, 0)))
diode_seat = diode_seat.cut(hole(2.35, 5, -5, 0, Z, (1, 0, 0)))
for y in (-6.5, 6.5):
    diode_seat = diode_seat.cut(hole(1.05, 5, -5, y, Z, (1, 0, 0)))
diode_riser = box(-7, -12, floor, 10, 24, Z - 9 - floor)
diode_riser = diode_riser.fuse(box(0, -12, Z - 10, 3, 24, 18))
diode_riser = diode_riser.cut(hole(3.25, 3, 0, 0, Z, (1, 0, 0)))
for y in (-6.5, 6.5):
    diode_riser = diode_riser.cut(hole(0.8, 3, 0, y, Z, (1, 0, 0)))
diode_clip = box(-6, -9, Z - 7, 1, 18, 14)
diode_clip = diode_clip.cut(hole(2.4, 1, -6, 0, Z, (1, 0, 0)))
for y in (-6.5, 6.5):
    diode_clip = diode_clip.cut(hole(1.05, 1, -6, y, Z, (1, 0, 0)))
for y in (-9, 9):
    base = base.cut(hole(1.65, floor, -4, y, 0))
    diode_riser = diode_riser.cut(hole(1.25, 5, -4, y, floor))

# Each Ø12 socket has two isolated blind bores, with the shoulder seating at
# the base of the shallow counterbore. The pilot below takes an M3 tap.
for x, y in head_xy:
    base = base.cut(hole(1.65, floor, x, y, 0))
head_socket = hole(6, head_seat - floor + 1, 0, 0, floor)
head_socket = head_socket.cut(hole(1.075, 5.3, 0, 0, head_seat - 5.3))
head_socket = head_socket.cut(hole(2.05, 1, 0, 0, head_seat))
head_socket = head_socket.cut(hole(1.25, 4.2, 0, 0, floor))

# Two long slots let the base mount slide for switch installation. The two
# cross holes match the 6.5 mm pitch of the D2F-01FL switch body.
home_x = mirror_x + 16
home_y = drive_y + 2.5
home_bracket = box(home_x - 6, home_y, floor, 24, 17, 5)
home_bracket = home_bracket.fuse(box(home_x + 2, home_y, floor + 3, 10, 3, Z-floor+3))
for x in (home_x, home_x + 14):
    slot = cq.Workplane("XY", origin=(x, home_y+10, floor)).slot2D(9, 3.3).extrude(5)
    home_bracket = home_bracket.cut(slot.val())
    base = base.cut(hole(1.65, floor, x, home_y + 10, 0))
for z in (Z - 7, Z - 0.5):
    home_bracket = home_bracket.cut(hole(1.1, 3, home_x + 8, home_y, z, (0, 1, 0)))

# Fixed upright and compliant hinge support the moving lever. Two free surfaces
# around the hinge permit bending in X; the hinge is wide in Z.
lever_x = mirror_x + 14
fixed = box(lever_x - 7, -13, floor, 35, 26, 5)
fixed = fixed.fuse(box(lever_x - 5, -18, floor + 3, 10, 9, Z + 5 - floor))
for y in (-9, 9):
    fixed = fixed.cut(hole(1.65, 5, mirror_x + 31, y, floor))
hinge = box(lever_x - 1.5, -10, Z - 7, 3, 10, 14)
lever = box(lever_x - 4, -1, Z - 7, 8, 51, 14)
lever = lever.fuse(box(lever_x - 4, -1, Z - 22, 5, 17, 44))
lever = lever.fuse(box(lever_x - 4, -13, Z + 12, 5, 30, 10))
lever = fixed.fuse(hinge, lever)
lever = lever.cut(hole(1.5, 4.4, lever_x - 4, 6, Z + 4, (1, 0, 0)))
lever = lever.cut(hole(0.45, 18, lever_x - 1, -1, Z + 4, (0, 1, 0)))

# Three M3 adjustment screws and a tension spring locate the mirror plate.
mirror_carrier = box(mirror_x + 4.9, -16, Z - 23, 4, 32, 46)
for y, z in ((0, Z - 21), (10, Z + 15), (-10, Z + 15)):
    mirror_carrier = mirror_carrier.cut(hole(1.25, 4, mirror_x + 4.9, y, z, (1, 0, 0)))

mirror_carrier = mirror_carrier.cut(
    hole(1.5, 4, mirror_x + 8.9, 6, Z + 4, (-1, 0, 0)))
mirror_carrier = mirror_carrier.cut(
    hole(0.45, 32, mirror_x + 6.4, -16, Z + 4, (0, 1, 0)))

# Post and threaded adjustment for the forward mechanical stop.
stop_bracket = box(mirror_x-6, drive_y-9, floor, 13, 18, 5)
stop_bracket = stop_bracket.fuse(box(mirror_x, drive_y-4, floor+3, 6, 8, Z-floor+4))
stop_bracket = stop_bracket.cut(hole(1.25, 6, mirror_x, drive_y, Z, (1,0,0)))
for dy in (-5,5):
    stop_bracket = stop_bracket.cut(hole(1.65, 5, mirror_x, drive_y+dy, floor))
stop_screw = hole(1.5, 10, mirror_x-0.55, drive_y, Z, (1,0,0))

# Motor flange and foot. Shaft faces back toward the lever.
flange_x = mirror_x + 73
motor_mount = box(flange_x - 30, drive_y - 24, floor, 36, 48, 5)
motor_mount = motor_mount.fuse(box(flange_x, drive_y - 24, floor + 3, 6, 48, Z - floor + 24))
# Captive nut block provides the fixed female thread for the moving screw.
nut_block = box(lever_x + 15, drive_y - 8, floor + 4, 9, 16, Z - floor + 4)
motor_mount = motor_mount.fuse(nut_block, box(lever_x + 15, drive_y - 8, floor, 40, 16, 5))
motor_mount = motor_mount.cut(hole(1.8, 9, lever_x + 15, drive_y, Z, (1, 0, 0)))
nut_pocket = cq.Workplane("YZ", origin=(lever_x + 22, drive_y, Z)).polygon(6, 6.55).extrude(2)
motor_mount = motor_mount.cut(nut_pocket.val())
motor_mount = motor_mount.cut(hole(11.25, 6, flange_x, drive_y, Z, (1, 0, 0)))
for y in (drive_y - 15.5, drive_y + 15.5):
    for z in (Z - 15.5, Z + 15.5):
        motor_mount = motor_mount.cut(hole(1.65, 6, flange_x, y, z, (1, 0, 0)))
    for x in (mirror_x + 48, mirror_x + 67):
        motor_mount = motor_mount.cut(hole(1.65, 5, x, y, floor))

for name, shape in (
    ("base", base), ("lens-saddle", lens_block), ("lever", lever),
    ("motor-mount", motor_mount), ("mirror-carrier", mirror_carrier),
    ("stop-bracket", stop_bracket), ("optic-strap", optic_strap),
    ("head-socket", head_socket), ("home-bracket", home_bracket),
    ("diode-riser", diode_riser), ("diode-seat", diode_seat),
    ("diode-clip", diode_clip)
):
    export_print(name, shape)

# Import the purchased motor. Rotate its catalog Z axis onto bench -X.
motor_face = flange_x + 6
motor_source = cq.importers.importStep(str(args.motor_step)).val().Solids()
motor = cq.Compound.makeCompound(
    [solid.rotate((0, 0, 0), (0, 1, 0), -90)
     .translate(cq.Vector(motor_face + 21.5, drive_y, Z)) for solid in motor_source[:3]]
)
# The routed lead solids in the catalog STEP are omitted because their shape
# depends on the installation. Route the real leads toward the plate edge.
screw_start = lever_x + 4
# Major diameter envelope of an M3 x 0.5 × 25 mm socket head cap screw.
screw = hole(1.5, 25, screw_start, drive_y, Z, (1, 0, 0))
screw_head = hole(2.75, 3, screw_start + 25, drive_y, Z, (1, 0, 0))
socket = cq.Workplane("YZ", origin=(screw_start + 26.5, drive_y, Z)).polygon(6, 2.89).extrude(1.5)
screw = screw.fuse(screw_head.cut(socket.val()))
# Sliding drive uses a captive 2.5 mm hex key stub, with axial clearance.
adapter_x = screw_start + 29
adapter = hole(5, motor_face - 10 - adapter_x, adapter_x, drive_y, Z, (1, 0, 0))
adapter = adapter.cut(hole(2.55, 10, motor_face - 20, drive_y, Z, (1, 0, 0)))
key = cq.Workplane("YZ", origin=(screw_start + 26.9, drive_y, Z)).polygon(6, 2.83).extrude(7)
key_pocket = cq.Workplane("YZ", origin=(adapter_x, drive_y, Z)).polygon(6, 3.00).extrude(4)
adapter = adapter.cut(key_pocket.val())
adapter = adapter.cut(hole(1.25, 3, motor_face-14, drive_y, Z+5, (0,0,-1)))
export_print("drive-adapter", adapter)
adjusters = [
    hole(1.5, 5.1, mirror_x + 4.9, y, z, (1, 0, 0))
    for y, z in ((0, Z - 21), (10, Z + 15), (-10, Z + 15))
]
mirror = (cq.importers.importStep(str(args.mirror_step)).val()
          .rotate((0, 0, 0), (0, 1, 0), 90)
          .translate(cq.Vector(mirror_x, 0, Z)))
lens = hole(args.lens_od / 2, 15.5, lens_exit - 15.5, 0, Z, (1, 0, 0))
lens = lens.cut(hole(5.0, 15.5, lens_exit - 15.5, 0, Z, (1, 0, 0)))

# Released KiCad STEP has inverted Y. Four actual corner pins sit on their
# shoulders, with the purchased board horizontal and components facing up.
head = cq.importers.importStep(str(args.head_step)).val()
head = head.translate(cq.Vector(-106, 56, 20))
head_bounds = head.BoundingBox()
assert abs(head_bounds.xlen - 82) < 0.01 and abs(head_bounds.ylen - 82) < 0.01
assert head_bounds.xmax < lens_block.BoundingBox().xmin
socket_centres = []
for x, y in head_xy:
    matching = [
        solid for solid in head.Solids()
        if abs(solid.BoundingBox().center.x - x) < 0.05
        and abs(solid.BoundingBox().center.y - y) < 0.05
        and abs(solid.BoundingBox().zmin - 11.245) < 0.05
    ]
    assert len(matching) == 1, (x, y, len(matching))
    fitted_socket = head_socket.translate(cq.Vector(x, y, 0))
    overlap = sum(solid.Volume() for solid in matching[0].intersect(fitted_socket).Solids())
    assert overlap < 0.01, (x, y, overlap)
    socket_centres.append({"x_mm": x, "y_mm": y, "pin_intersection_mm3": round(overlap, 6)})
assert all(
    solid.BoundingBox().zmin >= head_seat + 1 - 0.01
    for solid in head.Solids()
    if solid.BoundingBox().zmin > 11.30
)
checks = {
    "head_outline_mm": [round(head_bounds.xlen, 3), round(head_bounds.ylen, 3)],
    "head_socket_centres": socket_centres,
    "socket_seat_z_mm": head_seat,
    "pin_tip_to_bore_floor_mm": 0.55,
    "base_mm": [round(base.BoundingBox().xlen, 3), 185, floor],
    "beam_axis_z_mm": Z,
    "lens_to_mirror_mm": args.throw,
}
(args.out / "fit-checks.json").write_text(json.dumps(checks, indent=2) + "\n")

bench = cq.Assembly(name="Interferometer bench prototype")
for name, shape, rgb in (
    ("Bench base", base, (0.13, 0.17, 0.21)),
    ("Lens saddle", lens_block, (0.22, 0.36, 0.45)),
    ("Lever", lever, (0.16, 0.4, 0.47)),
    ("Motor bracket", motor_mount, (0.22, 0.36, 0.45)),
    ("17HS08-1004S motor", motor, (0.19, 0.19, 0.2)),
    ("M3 leadscrew", screw, (0.65, 0.67, 0.71)),
    ("Hex drive stub", key, (0.65, 0.67, 0.71)),
    ("Travel stop", stop_bracket, (0.22, 0.36, 0.45)),
    ("Travel stop screw", stop_screw, (0.65, 0.67, 0.71)),
    ("Drive adapter", adapter, (0.16, 0.4, 0.47)),
    ("Insulating diode riser", diode_riser, (0.22, 0.36, 0.45)),
    ("Insulated TO-56 rear clip", diode_clip, (0.22, 0.36, 0.45)),
    ("Machined TO-56 diode seat", diode_seat, (0.67, 0.68, 0.71)),
    ("Lens clamp strap", optic_strap, (0.22, 0.36, 0.45)),
    ("HOME switch bracket", home_bracket, (0.22, 0.36, 0.45)),
    ("SM05L05 barrel envelope", lens, (0.15, 0.15, 0.16)),
    ("Mirror carrier", mirror_carrier, (0.22, 0.36, 0.45)),
    ("Mirror", mirror, (0.72, 0.76, 0.79)),
    ("Released 1.3 laser head", head, (0.048, 0.33, 0.20)),
):
    bench.add(shape, name=name, color=cq.Color(*rgb))
for index, (x, y) in enumerate(head_xy, 1):
    bench.add(head_socket.translate(cq.Vector(x, y, 0)),
              name=f"Insulated head socket {index}", color=cq.Color(0.24, 0.40, 0.50))
for index, adjuster in enumerate(adjusters, 1):
    bench.add(adjuster, name=f"Mirror adjuster {index}", color=cq.Color(0.65, 0.67, 0.71))
bench.export(str(args.out / "bench-prototype.step"))