"""Draws app/wiring.png: how to connect the laptop, USB hub, 12 V supply, 5 stepper boards,
motors and limit switches. Written by Claude for Andrin.

Pinout source: modular-things "stepper-hbridge-xiao" reference design (schematic of 2023-07-25),
the board the UFP stepper firmware (Quentin Bolsee) is written for, and Tudor Mocioi's
firmware/README.md (jumper, 5 to 12 V, current <= 0.2 on USB, limit switch NC to SIG).
Check the silkscreen of your boards if they are a different revision.

Run:  python make_wiring_diagram.py   (rewrites wiring.png)
"""
from pathlib import Path

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import FancyBboxPatch, Rectangle

OUT = Path(__file__).with_name("wiring.png")
RED, BLK, BLU, GRN, GRY = "#c0392b", "#1f2937", "#2563eb", "#15803d", "#6b7280"


def box(ax, x, y, w, h, text, fc="#f3f4f6", ec=BLK, fs=9, bold=False, lw=1.2):
    ax.add_patch(FancyBboxPatch((x, y), w, h, boxstyle="round,pad=0,rounding_size=1.2",
                                fc=fc, ec=ec, lw=lw))
    ax.text(x + w / 2, y + h / 2, text, ha="center", va="center", fontsize=fs,
            fontweight="bold" if bold else "normal")


def line(ax, pts, color=BLK, lw=1.8, ls="-"):
    xs, ys = zip(*pts)
    ax.plot(xs, ys, color=color, lw=lw, ls=ls, solid_capstyle="round", zorder=1)


def pin(ax, x, y, text="", fc="#fde68a", s=3.0, fs=8):
    ax.add_patch(Rectangle((x - s / 2, y - s / 2), s, s, fc=fc, ec=BLK, lw=0.9, zorder=3))
    if text:
        ax.text(x, y, text, ha="center", va="center", fontsize=fs, zorder=4)


def board_detail(ax):
    ax.text(2, 97, "One stepper board", fontsize=13, fontweight="bold")
    ax.text(2, 93.5, "all 5 boards are the same, only the MOTOR_ID in the firmware differs",
            fontsize=9, color=GRY)
    # board
    ax.add_patch(FancyBboxPatch((24, 22), 34, 52, boxstyle="round,pad=0,rounding_size=2.5",
                                fc="#dcfce7", ec=GRN, lw=1.8, zorder=0))
    ax.text(41, 34, "XIAO RP2040\n+ 2 H-bridges\n(bolts onto the\nNEMA 17)", ha="center", va="center",
            fontsize=8.5, color=GRN)
    # USB-C
    box(ax, 36, 72.5, 10, 4, "USB-C", fc="#e5e7eb", fs=8.5, bold=True)
    line(ax, [(41, 76.5), (41, 82)], BLU, 2.2)
    ax.text(41, 86, "to the powered USB hub\n(data, and 5 V for the XIAO)", ha="center", va="center",
            fontsize=8.5, color=BLU)

    # J1 2x4 IDC on the left edge
    ax.text(26, 68, "J1  2x4 IDC", fontsize=9, fontweight="bold")
    rows = [(63, "1", "2"), (58.5, "3", "4"), (54, "5", "6"), (49.5, "7", "8")]
    even_col = {"2": "#e5e7eb", "4": "#9ca3af", "6": "#9ca3af", "8": "#fca5a5"}
    for y, o, e in rows:
        pin(ax, 28, y, o, fc="#e5e7eb")
        pin(ax, 32, y, e, fc=even_col[e])
    line(ax, [(33.5, 49.5), (36, 49.5), (36, 44), (21, 44)], RED, 1.4)
    line(ax, [(33.5, 58.5), (35, 58.5), (35, 40), (21, 40)], BLK, 1.4)
    ax.text(20, 44, "pin 8: +12 V in", ha="right", va="center", fontsize=9, color=RED, fontweight="bold")
    ax.text(20, 40, "pin 4 or 6: GND", ha="right", va="center", fontsize=9, fontweight="bold")
    ax.text(20, 35.5, "pin 2: board's USB 5 V,\nleave it open", ha="right", va="center", fontsize=8,
            color=GRY)
    ax.text(20, 30.5, "pins 1, 3, 5, 7: not used\n(old modular-things bus)", ha="right", va="center",
            fontsize=8, color=GRY)

    # J2 jumper
    ax.text(40, 68, "J2  power select", fontsize=9, fontweight="bold")
    for x, lab in [(43, "VUSB"), (47.5, "VCC"), (52, "BP_VCC")]:
        pin(ax, x, 64, fc="#fde68a")
        ax.text(x, 60.8, lab, ha="center", va="center", fontsize=7)
    ax.add_patch(Rectangle((46, 62.4), 7.5, 3.2, fc="#facc15", ec=BLK, lw=1, alpha=0.85, zorder=5))
    ax.text(49.75, 64, "jumper", ha="center", va="center", fontsize=6.5, zorder=6)
    line(ax, [(53.5, 64), (60, 64), (60, 70)], RED, 1.2)
    ax.text(61, 71, "with 12 V on J1: jumper on VCC + BP_VCC\nNEVER on VUSB while 12 V is connected",
            fontsize=8.2, color=RED, va="bottom")

    # J4 limit switch on the right edge
    ax.text(47, 55.5, "J4  limit", fontsize=9, fontweight="bold")
    for y, lab, col in [(51.5, "3V3: only for optical / Hall sensors", "#e5e7eb"),
                        (47, "GND: to switch COM", "#9ca3af"),
                        (42.5, "SIG: to switch NC (normally closed)", "#bfdbfe")]:
        pin(ax, 55, y, fc=col)
        line(ax, [(56.5, y), (61, y)], GRY, 1)
        ax.text(62, y, lab, va="center", fontsize=8.5)
    ax.text(62, 35.5, "pressed or unplugged = limit True\n"
            "only on the two XY boards\n"
            "on the board: 3 holes at the edge,\n"
            "SIG, GND, 3V3 from the USB side", fontsize=8, color=GRY, va="center")

    # J3 motor at the bottom edge
    ax.text(31, 28.5, "J3  motor", fontsize=9, fontweight="bold")
    for i, (n, sig, col) in enumerate([("1", "OB2", "#bfdbfe"), ("2", "OB1", "#bfdbfe"),
                                       ("3", "OA1", "#fecaca"), ("4", "OA2", "#fecaca")]):
        x = 33 + i * 5
        pin(ax, x, 24.5, n, fc=col, s=3.4)
        ax.text(x, 19.5, sig, ha="center", fontsize=7.5)
    line(ax, [(31.5, 17.5), (39.5, 17.5)], BLU, 2)
    line(ax, [(41.5, 17.5), (49.5, 17.5)], RED, 2)
    ax.text(35.5, 15, "coil B", ha="center", fontsize=8.5, color=BLU)
    ax.text(45.5, 15, "coil A", ha="center", fontsize=8.5, color=RED)
    ax.text(41, 11.5, "Find the coil pairs with a multimeter: 1 to 3 ohm across one coil, open between\n"
            "coils. Swapping a pair only reverses the direction (or set invert_a / invert_b).",
            ha="center", va="top", fontsize=8.5)


def system(ax):
    X0 = 92
    ax.text(X0, 97, "Whole machine", fontsize=13, fontweight="bold")
    ax.text(X0, 93.5, "1 laptop, 1 powered USB hub, 1 x 12 V supply, 5 boards", fontsize=9, color=GRY)
    box(ax, 116, 82, 26, 8, "Laptop\nsimple_gui.py", fc="#dbeafe", fs=9.5, bold=True)
    box(ax, 114, 69, 30, 8, "powered USB hub\n(one cable to the laptop)", fc="#dbeafe", fs=9)
    line(ax, [(129, 82), (129, 77)], BLU, 2.4)
    boards = [("Motor A\nID 1\nCoreXY", 93), ("Motor B\nID 2\nCoreXY", 107), ("Syringe 0\nID 3\ndark", 121),
              ("Syringe 1\nID 4\nmedium", 135), ("Syringe 2\nID 5\nlight", 149)]
    w = 12
    line(ax, [(93 + w / 2, 64), (149 + w / 2, 64)], BLU, 2.4)
    line(ax, [(129, 69), (129, 64)], BLU, 2.4)
    for text, x in boards:
        line(ax, [(x + w / 2, 64), (x + w / 2, 58)], BLU, 2.4)
        box(ax, x, 44, w, 14, text, fc="#dcfce7", ec=GRN, fs=8.5)
        line(ax, [(x + w - 2, 44), (x + w - 2, 30)], RED, 2.4)
    line(ax, [(93 + w - 2, 30), (149 + w - 2, 30)], RED, 2.4)
    line(ax, [(129, 30), (129, 24)], RED, 2.4)
    box(ax, 114, 15, 30, 9, "12 V supply, >= 5 A\n+ and - to a terminal block", fc="#fee2e2", ec=RED, fs=9)
    ax.text(146, 27, "to each board:\nJ1 pin 8 (+), pin 4 (-)", fontsize=8, color=RED, va="top")
    for x, lab in [(93, "Y switch\nfront rail"), (107, "X switch\ngantry end")]:
        box(ax, x - 0.5, 34, 8, 7, lab, fc="#e0f2fe", ec=BLU, fs=7)
        line(ax, [(x + 3.5, 41), (x + 3.5, 44)], GRY, 1.2)
    ax.text(X0, 10, "Blue: USB data.  Red: 12 V motor power, wired as a star: one pair of wires per board\n"
            "from the terminal block (no daisy chained ribbon cable). Motors sit on J3 of their board.\n"
            "Limit switches: Y on the front rail, X under the right end of the gantry, each on J4 of one XY board\n"
            "(Find boards / turn shows which board is which; the status line shows the switches). COM to GND, NC to SIG.",
            fontsize=8.5, va="top")


def rules(ax):
    ax.text(2, -2, "Rules and bring-up order", fontsize=13, fontweight="bold")
    txt = (
        "1  Never leave the J2 jumper on VUSB while 12 V is on J1: that puts 12 V on the XIAO and on the laptop's USB.\n"
        "2  Never plug or unplug a motor while its board is powered (the H-bridge can die).\n"
        "3  USB power only (no 12 V): currents <= 0.2, set the motor currents to 0.2 in the window.\n"
        "4  Each board needs its MOTOR_ID flashed (third_party/ufp/arduino/UFP/examples/ufp_stepper, #define MOTOR_ID).\n"
        "   Plan of the team: 1 = motor A, 2 = motor B, 3 to 5 = syringes 0 to 2.\n"
        "5  Bring-up: one board on USB at 0.2, check its direction with the jog buttons -> jumper to BP_VCC, 12 V on ->\n"
        "   raise the current step by step -> wire the gantry -> Scan USB -> Connect -> jog -> dry run -> print.\n"
        "6  STOP button or Esc stops all motors. Keep a hand on the 12 V switch during the first runs.\n"
        "Pinout from the modular-things stepper-hbridge-xiao design (2023-07-25): check the J2 outer pins with a multimeter."
    )
    ax.text(2, -6, txt, fontsize=9.2, va="top", family="monospace")


def main():
    fig = plt.figure(figsize=(17, 12.6), dpi=100)
    ax = fig.add_axes([0.01, 0.01, 0.98, 0.95])
    ax.set_xlim(0, 166)
    ax.set_ylim(-26, 100)
    ax.set_aspect("equal")
    ax.axis("off")
    line(ax, [(88, 5), (88, 98)], "#d1d5db", 1)
    board_detail(ax)
    system(ax)
    rules(ax)
    fig.suptitle("Pancake printer wiring (MAS.863 EECS section, machine week)", fontsize=15,
                 fontweight="bold", x=0.015, ha="left", y=0.985)
    fig.savefig(OUT, facecolor="white", dpi=100)
    print(f"wrote {OUT}")


if __name__ == "__main__":
    main()
