"""Schematics for the 19 mm round 2-board driver stack, drawn with real wires.

    python gen_stack_sch.py <project dir> s1|s2

Stack, bottom to top (both boards 19 mm round, same 2x6 1.27 mm bus position):
  S1 Power : controller link (J1, bottom), INA236 input monitor + shunt, LMR33640 buck VIN -> VLED_UV
  S2 Driver: AD5693R DAC, iC-HG30 current sink, shunt + INA209, strobe inverter, D6, LED wire pads

Drawing style: wires inside each circuit block, power symbols for rails/GND, net labels only on the bus
connector pins, I2C and the strobe signal (and as small names on internal nets). All coordinates are on the
1.27 mm grid. Refdes are unique across the stack.
"""
import os, sys, json
sys.path.insert(0, os.path.dirname(__file__))
import kgen
from kgen import Schematic

D, BOARD = sys.argv[1], sys.argv[2]
kgen.PROJ_LIBS['XFM5050UV'] = os.path.join(D, '..', 'lib', 'XFM5050UV.kicad_sym')
NC = None
R0402, C0402, C0603, C1210 = ('Resistor_SMD:R_0402_1005Metric', 'Capacitor_SMD:C_0402_1005Metric',
                              'Capacitor_SMD:C_0603_1608Metric', 'Capacitor_SMD:C_1210_3225Metric')
HDR = 'Connector_PinHeader_1.27mm:PinHeader_2x06_P1.27mm_Vertical_SMD'
SKT = 'Connector_PinSocket_1.27mm:PinSocket_2x06_P1.27mm_Vertical_SMD'
WIRE_PAD = 'TestPoint:TestPoint_Pad_3.0x3.0mm'
POWER = {'VIN', '5V_reg', '3V3_reg', 'VLED_UV', 'VLED_BUCK_IN'}

# 2x6 1.27 mm bus, identical pin positions on both boards (odd = one row, even = the other).
BUS = {'1': 'VIN', '2': 'VIN', '3': 'GND', '4': 'GND', '5': 'VLED_UV', '6': 'VLED_UV',
       '7': '5V_reg', '8': '3V3_reg', '9': 'SDA', '10': 'SCL', '11': 'ENABLE_0', '12': 'GND'}

TITLES = {'s1': ('XFM5050UV-S1-Power', 'XFM-5050-UV stack 1/2: input monitor + LED rail buck'),
          's2': ('XFM5050UV-S2-Driver', 'XFM-5050-UV stack 2/2: DAC + iC-HG30 current sink')}
name, title = TITLES[BOARD]
s = Schematic(name, title, 'C', '2026-11-12', company='MBARI',
              comments=('19 mm round board, part of a 2-board stack (S1 bottom, S2 top)',
                        'LED: Luminus XFM-5050-UV-D130, 275 nm UV-C, 2 A typ / 3.2 A max'))


# ---------------------------------------------------------------- helpers
def R(ref, val, x, y, n1, n2, rot=0, fp=R0402, **kw):
    s.place('Device:R', ref, val, x, y, {'1': n1, '2': n2}, rot=rot, fp=fp, **kw)


def C(ref, val, x, y, n1, n2, rot=0, fp=C0402, **kw):
    s.place('Device:C', ref, val, x, y, {'1': n1, '2': n2}, rot=rot, fp=fp, **kw)


def P(ref, num):
    return s.P(ref, num)


def W(*pts):
    s.wire(*pts)


def gnd(pt, toward='down'):
    s.pwr('GND', pt[0], pt[1], toward)


def rail(net, pt, toward='up'):
    s.pwr(net, pt[0], pt[1], toward)


def stub(pt, dx, dy):
    e = (round(pt[0] + dx, 2), round(pt[1] + dy, 2))
    W(pt, e)
    return e


def cap_to_gnd(ref, val, x, ytop, net, fp=C0402):
    """Vertical capacitor whose top pin is at (x, ytop) on `net`, bottom pin to a GND symbol."""
    C(ref, val, x, ytop + 3.81, net, 'GND', fp=fp)
    gnd(P(ref, 2))


def flag(net, x, y):
    """Power symbol at (x, y) with a PWR_FLAG 5.08 mm to its right, joined by a wire."""
    if net == 'GND':
        gnd((x, y))
    else:
        rail(net, (x, y), 'up')
    W((x, y), (x + 5.08, y))
    s.pflag(net, x + 5.08, y)


def bus(ref, val, x, y, fp, override=None):
    """2x6 bus connector; each pin gets a 5.08 mm stub ending in a power symbol (rails/GND) or a label."""
    nets = dict(BUS)
    nets.update(override or {})
    s.place('Connector_Generic:Conn_02x06_Odd_Even', ref, val, x, y, nets, fp=fp,
            ref_at=(x - 3.81, y - 11.43), val_at=(x - 3.81, y - 8.89))
    for n in range(1, 13):
        net = nets[str(n)]
        if net is None:
            continue
        left = n % 2 == 1
        e = stub(P(ref, n), -5.08 if left else 5.08, 0)
        side = 'left' if left else 'right'
        if net == 'GND':
            gnd(e, side)
        elif net in POWER:
            rail(net, e, side)
        else:
            s.label(net, e[0], e[1], side)


def note(txt, x, y, size=1.27):
    s.text(txt, x, y, size)


def heading(txt, x, y):
    s.text(txt, x, y, 2.0)


def desc(txt, x, y):
    """Italic one- or two-sentence description of what a part does, placed next to it."""
    s.text(txt, x, y, 1.27, italic=True)


# ================================================================= S1 POWER
if BOARD == 's1':
    # --- connectors
    heading('CONTROLLER LINK  (J1, BOTTOM side of S1)', 22.86, 45.72)
    bus('J1', 'Controller link', 38.1, 63.5, HDR, {'5': NC, '6': NC})
    heading('BUS TO S2  (J2, TOP side of S1)', 22.86, 99.06)
    bus('J2', 'Bus to S2', 38.1, 116.84, HDR, {'1': NC, '2': NC})

    # --- input monitor: VIN -> R5 shunt -> VLED_BUCK_IN, INA236 across the shunt
    heading('INPUT MONITOR', 76.2, 40.64)
    s.place('XFM5050UV:INA236', 'U2', 'INA236AIDDFR', 114.3, 66.04,
            {'1': 'VIN', '2': 'VLED_BUCK_IN', '3': 'GND', '4': '3V3_reg', '5': 'SCL', '6': 'SDA', '7': 'GND', '8': NC},
            fp='Package_TO_SOT_SMD:SOT-23-8', props={'MPN': 'INA236AIDDFR', 'Manufacturer': 'Texas Instruments'},
            ref_at=(116.84, 54.61), val_at=(116.84, 80.01))
    R('R5', '10mR 1% 0805', 93.98, 86.36, 'VIN', 'VLED_BUCK_IN', rot=90, fp='Resistor_SMD:R_0805_2012Metric',
      ref_at=(91.44, 82.55), val_at=(88.9, 91.44))
    rail('VIN', (76.2, 86.36), 'up')
    # VIN rail with PWR_FLAG, branch to IN+
    W((76.2, 86.36), (80.01, 86.36), (85.09, 86.36), P('R5', 1))
    s.pflag('VIN', 80.01, 86.36)
    W((85.09, 86.36), (85.09, 63.5), P('U2', 1))
    # after the shunt: branch to IN-, then on to the buck (VLED_BUCK_IN rail)
    W(P('R5', 2), (101.6, 86.36))
    W((101.6, 86.36), (101.6, 68.58), P('U2', 2))
    # VS: 3V3 + C1
    W(P('U2', 4), (114.3, 50.8), (114.3, 48.26))
    rail('3V3_reg', (114.3, 48.26), 'up')
    W((114.3, 50.8), (109.22, 50.8), (104.14, 50.8))
    s.pflag('3V3_reg', 109.22, 50.8)
    cap_to_gnd('C1', '100nF', 104.14, 50.8, '3V3_reg')
    gnd(P('U2', 3))
    s.label('SCL', *stub(P('U2', 5), 5.08, 0), 'right')
    s.label('SDA', *stub(P('U2', 6), 5.08, 0), 'right')
    gnd(stub(P('U2', 7), 5.08, 0), 'right')
    note('U2 INA236A: A0 = GND -> I2C 0x40.\nUse the +/-81.92 mV range\n(1.6 A typ = 16 mV on R5).', 129.54, 40.64)

    # --- buck: VLED_BUCK_IN rail along y = 86.36
    heading('LED RAIL BUCK', 139.7, 73.66)
    s.place('Regulator_Switching:LMR33640ADDA', 'U3', 'LMR33640ADDA', 223.52, 91.44,
            {'1': 'GND', '9': 'GND', '2': 'VLED_BUCK_IN', '3': 'BUCK_EN', '4': NC, '5': 'BUCK_FB', '6': 'BUCK_VCC',
             '7': 'BUCK_BOOT', '8': 'BUCK_SW'}, fp='XFM5050UV:Texas_HSOP-8-1EP_ThermalVias_1col',
            ref_at=(215.9, 80.01), val_at=(226.06, 105.41))
    C('C4', '10uF 50V', 139.7, 90.17, 'VLED_BUCK_IN', 'GND', fp=C1210)
    C('C5', '10uF 50V', 154.94, 90.17, 'VLED_BUCK_IN', 'GND', fp=C1210)
    C('C6', '100nF 50V', 170.18, 90.17, 'VLED_BUCK_IN', 'GND')
    R('R1', '100k', 187.96, 90.17, 'VLED_BUCK_IN', 'BUCK_EN')
    R('R2', '13.7k', 187.96, 97.79, 'BUCK_EN', 'GND')
    W((101.6, 86.36), (132.08, 86.36), P('C4', 1), P('C5', 1), P('C6', 1), P('R1', 1), P('U3', 2))
    s.label('VLED_BUCK_IN', 106.68, 86.36, 'right')
    s.pflag('VLED_BUCK_IN', 132.08, 86.36)
    for c in ('C4', 'C5', 'C6'):
        gnd(P(c, 2))
    gnd(P('R2', 2))
    W(P('R1', 2), (198.12, 93.98), (198.12, 91.44), P('U3', 3))
    C('C7', '1uF 16V', 203.2, 100.33, 'BUCK_VCC', 'GND')
    W(P('U3', 6), P('C7', 1))
    gnd(P('C7', 2))
    gnd(P('U3', 1))
    # boot cap and switch node
    C('C8', '100nF', 243.84, 85.09, 'BUCK_BOOT', 'BUCK_SW', ref_at=(241.3, 76.2), val_at=(241.3, 78.74))
    W(P('U3', 7), (238.76, 86.36), (238.76, 81.28), P('C8', 1))
    s.place('Device:L', 'L1', '10uH XAL5050-103', 256.54, 88.9, {'1': 'BUCK_SW', '2': 'VLED_UV'}, rot=90,
            fp='Inductor_SMD:L_Coilcraft_XAL5050-XXX', props={'MPN': 'XAL5050-103MEC', 'Manufacturer': 'Coilcraft'},
            ref_at=(252.73, 83.82), val_at=(252.73, 81.28))
    W(P('U3', 8), P('C8', 2), P('L1', 1))
    s.label('BUCK_SW', 245.11, 88.9, 'right')
    # output rail VLED_UV, feedback divider, output caps
    R('R3', '100k 1%', 264.16, 92.71, 'VLED_UV', 'BUCK_FB')
    R('R4', '14.0k 1%', 264.16, 100.33, 'BUCK_FB', 'GND')
    outs = ['C10', 'C11', 'C12', 'C13']
    for i, ref in enumerate(outs):
        C(ref, '22uF 25V', 279.4 + i * 15.24, 92.71, 'VLED_UV', 'GND', fp=C1210)
    W(P('L1', 2), P('R3', 1), *[P(r, 1) for r in outs], (340.36, 88.9))
    rail('VLED_UV', (340.36, 88.9), 'up')
    for ref in outs:
        gnd(P(ref, 2))
    gnd(P('R4', 2))
    W(P('U3', 5), (238.76, 93.98), (238.76, 96.52), P('R3', 2))
    note('VLED_UV = 1.0 V x (1 + R3/R4) = 8.14 V with R4 = 14.0k.\n'
         'Match R4 to the LED Vf bin (bin max + ~1.2 V):\n'
         '  V3 17.4k  V4 16.0k  V5 14.7k  V6 14.0k  V7 13.0k  V8 12.1k\n'
         'EN UVLO ~10 V via R1/R2; VIN must be 11-36 V.\n'
         'L1 XAL5050-103: Isat 4.9 A, Irms 3.6 A; peak ~2.8 A at 36 V in.\n'
         'U3 sits on the bottom side directly under L1 (single via column).', 264.16, 116.84)

    # --- what each part does
    desc('Ribbon from the controller: brings in VIN,\nGND, the 5 V / 3.3 V logic rails, I2C and\n'
         'ENABLE_0 (the strobe input).', 22.86, 76.2)
    desc('Stack connector up to S2: passes VLED_UV,\nthe logic rails, I2C and ENABLE_0.', 22.86, 129.54)
    desc('R5: 10 mOhm shunt that carries all of the\ninput current; U2 measures the voltage across it.',
         76.2, 96.52)
    desc('U2 INA236: input power monitor. Reports VIN\nvoltage, current and power over I2C.', 129.54, 30.48)
    desc('C4-C6: buck input capacitors; they supply\nthe switching current pulses U3 draws.', 139.7, 104.14)
    desc('R1/R2: enable divider, turns U3 on above\n~10 V.  C7: decoupling for U3\'s internal LDO.',
         180.34, 111.76)
    desc('U3 LMR33640: synchronous buck converter that steps\nVIN (11-36 V) down to the 8.14 V LED rail (VLED_UV).',
         205.74, 55.88)
    desc('C8: bootstrap capacitor that powers U3\'s high-side switch.', 205.74, 62.23)
    desc('L1: buck inductor; stores energy each\nswitching cycle to feed the LED rail.', 266.7, 73.66)
    desc('R3/R4: feedback divider that sets the\nLED rail voltage (see table below).', 264.16, 109.22)
    desc('C10-C13: output capacitors; smooth VLED_UV\nand supply fast current steps when strobing.',
         279.4, 101.6)

    # --- notes
    note('S1 POWER (bottom of stack)\n'
         'J1 (BOTTOM side) takes the controller ribbon: VIN 11-36 V, GND, 5V_reg, 3V3_reg,\n'
         '  SDA, SCL, ENABLE_0. Pins 5-6 (VLED_UV) are not connected.\n'
         'J2 (TOP side) carries VLED_UV, 5V_reg, 3V3_reg, I2C, ENABLE_0 and GND up to S2;\n'
         '  VIN pins 1-2 are not connected.\n'
         'BUS (2x6 1.27 mm, same XY on both boards): 1,2 VIN | 3,4,12 GND | 5,6 VLED_UV |\n'
         '  7 5V_reg | 8 3V3_reg | 9 SDA | 10 SCL | 11 ENABLE_0\n'
         'No bulk electrolytic on VIN: do not hot-plug VIN through long leads (ringing).\n'
         'UV-C (275 nm) is hazardous to eyes and skin.', 76.2, 140.97)
    for i, net in enumerate(['GND', '5V_reg', 'VLED_UV']):
        flag(net, 76.2 + i * 20.32, 210.82)

# ================================================================= S2 DRIVER
elif BOARD == 's2':
    heading('BUS FROM S1  (J1, BOTTOM side of S2)', 22.86, 45.72)
    bus('J1', 'Bus from S1', 38.1, 63.5, SKT, {'1': NC, '2': NC})

    # --- DAC: AD5693R, VOUT -> R11/R17 -> CI1
    heading('CURRENT-SET DAC', 40.64, 83.82)
    s.place('XFM5050UV:AD5693R_LFCSP', 'U4', 'AD5693RACPZ-RL7', 81.28, 96.52,
            {'1': '5V_reg', '2': 'GND', '3': 'GND', '4': 'GND', '5': 'SCL', '6': 'SDA', '7': 'DAC_VREF',
             '8': 'VCI1', '9': 'GND'},
            fp='Package_DFN_QFN:DFN-8-1EP_2x2mm_P0.5mm_EP0.6x1.2mm',
            props={'Datasheet': 'https://www.analog.com/media/en/technical-documentation/data-sheets/AD5693R_5692R_5691R_5693.pdf',
                   'MPN': 'AD5693RACPZ-RL7', 'Manufacturer': 'Analog Devices'},
            ref_at=(55.88, 109.22), val_at=(55.88, 111.76))
    W(P('U4', 1), (81.28, 81.28), (81.28, 78.74))
    rail('5V_reg', (81.28, 78.74), 'up')
    W((81.28, 81.28), (91.44, 81.28), (101.6, 81.28))
    C('C15', '100nF', 91.44, 85.09, '5V_reg', 'GND')
    C('C16', '10uF 10V', 101.6, 85.09, '5V_reg', 'GND', fp=C0603)
    gnd(P('C15', 2)); gnd(P('C16', 2))
    s.label('SCL', *stub(P('U4', 5), -5.08, 0), 'left')
    s.label('SDA', *stub(P('U4', 6), -5.08, 0), 'left')
    W(P('U4', 4), (66.04, 99.06), (66.04, 101.6), (66.04, 104.14))
    W(P('U4', 2), (66.04, 101.6))
    gnd((66.04, 104.14))
    W(P('U4', 3), (78.74, 109.22), (81.28, 109.22), (83.82, 109.22), P('U4', 9))
    gnd((81.28, 109.22))
    C('C3', '10nF', 96.52, 102.87, 'DAC_VREF', 'GND')
    W(P('U4', 7), P('C3', 1))
    gnd(P('C3', 2))
    R('R11', '11.3k 1%', 109.22, 93.98, 'VCI1', 'CI1', rot=90, ref_at=(106.68, 97.79), val_at=(106.68, 100.33))
    R('R17', '4.7k 1%', 116.84, 97.79, 'CI1', 'GND')
    W(P('U4', 8), P('R11', 1))
    s.label('VCI1', 96.52, 93.98, 'up')
    gnd(P('R17', 2))
    note('U4 AD5693RACPZ: I2C 0x4C (A0 = GND), ~LDAC = GND (updates on write).\n'
         'Internal 2.5 V ref is on at power-up; set GAIN = 2 in the control\n'
         'register for a 0-5 V span. Powers up at 0 V.\n'
         'CI = 0.29 x VCI1 -> ~1.43 V at 5 V full scale.', 55.88, 127.0)
    desc('U4 AD5693R: 16-bit DAC; its output sets the LED current.\n'
         'R11/R17 scale its 0-5 V output into the iC-HG30 CI input range.\n'
         'C3: reference bypass. C15/C16: supply decoupling.', 55.88, 116.84)
    desc('Stack connector from S1: brings in VLED_UV,\nthe logic rails, I2C and ENABLE_0.', 22.86, 74.93)

    # --- iC-HG30
    heading('CURRENT SINK  (iC-HG30, 4 channels in parallel)', 147.32, 50.8)
    desc('U5 iC-HG30: fast low-side current sink in the LED cathode path. CI1-4 set the\n'
         'current, EN1-4 switch it on/off in ~1 ns (strobing); LDK1-4 sink the LED current.', 147.32, 55.88)
    desc('R23, C17-C19:\nU5 supply filter', 165.1, 76.2)
    desc('R25: 20 mOhm sense resistor\nin the LED current return path.', 213.36, 186.69)
    hg = {'18': 'HG_VDD', '19': 'GND', '22': NC, '4': 'GND', '29': 'GND'}
    for ci in ['1', '2', '3', '5']:
        hg[ci] = 'CI1'
    for en in ['21', '20', '17', '16']:
        hg[en] = 'HG_EN'
    for p in ['27', '25', '23', '13']:
        hg[p] = 'LED_K'
    for p in ['6', '7', '15', '14']:
        hg[p] = 'GND'
    for p in ['11', '9']:
        hg[p] = NC
    for p in ['28', '26', '24', '12', '10', '8']:
        hg[p] = 'SHUNT_HI'
    s.place('XFM5050UV:iC-HG30', 'U5', 'iC-HG30', 190.5, 120.65, hg,
            fp='Package_DFN_QFN:QFN-28-1EP_5x5mm_P0.5mm_EP3.75x3.75mm_ThermalVias',
            ref_at=(193.04, 76.2), val_at=(193.04, 194.31))
    # CI1-CI4 bus (x = 161.29), fed from the DAC divider along y = 93.98
    ci_pins = ['1', '2', '3', '5']
    W(P('R11', 2), P('R17', 1), (161.29, 93.98), P('U5', 1))
    for p in ci_pins[1:]:
        W(P('U5', p), (161.29, P('U5', p)[1]))
    W(*[(161.29, P('U5', p)[1]) for p in ci_pins])
    s.label('CI1', 147.32, 93.98, 'up')
    # EN1-EN4 bus (x = 156.21) down to the strobe inverter
    en_pins = ['21', '20', '17', '16']
    for p in en_pins:
        W(P('U5', p), (156.21, P('U5', p)[1]))
    # unused channels and ELVDS to GND (x = 166.37)
    gpins = ['6', '15', '7', '14', '19']
    for p in gpins:
        W(P('U5', p), (166.37, P('U5', p)[1]))
    W(*[(166.37, P('U5', p)[1]) for p in gpins], (166.37, 167.64))
    gnd((166.37, 167.64))
    # VDD: 5V_reg -> R23 -> HG_VDD with C17-C19
    R('R23', '0R', 180.34, 68.58, '5V_reg', 'HG_VDD', rot=90, ref_at=(177.8, 64.77), val_at=(177.8, 62.23))
    W(P('R23', 1), (171.45, 68.58))
    rail('5V_reg', (171.45, 68.58), 'up')
    hgc = [('C17', '100nF', C0402), ('C18', '10nF', C0402), ('C19', '10uF 10V', C0603)]
    for i, (ref, val, fp) in enumerate(hgc):
        C(ref, val, 198.12 + i * 10.16, 72.39, 'HG_VDD', 'GND', fp=fp)
        gnd(P(ref, 2))
    W(P('R23', 2), (190.5, 68.58), *[P(r[0], 1) for r in hgc])
    W((190.5, 68.58), P('U5', 18))
    # bottom GND pins
    W(P('U5', 29), (190.5, 189.23), (193.04, 189.23), P('U5', 4))
    gnd((190.5, 189.23))
    # LDK1-4 -> LED_K bus (x = 219.71) up to the LED- pad and D6
    ldk = ['27', '25', '23', '13']
    for p in ldk:
        W(P('U5', p), (219.71, P('U5', p)[1]))
    W((219.71, P('U5', '13')[1]), *[(219.71, P('U5', p)[1]) for p in reversed(ldk[:-1])], (219.71, 81.28))
    # AGND1-6 -> SHUNT_HI bus (x = 224.79) down to R25
    ag = ['28', '26', '24', '12', '10', '8']
    for p in ag:
        W(P('U5', p), (224.79, P('U5', p)[1]))
    s.place('Device:R_Shunt', 'R25', '20mR WSK2512', 224.79, 170.18,
            {'1': 'SHUNT_HI', '2': 'SHUNT_SP', '3': 'SHUNT_SN', '4': 'GND'},
            fp='Resistor_SMD:R_Shunt_Vishay_WSK2512_6332Metric_T1.19mm', ref_at=(214.63, 168.91), val_at=(203.2, 171.45))
    W(*[(224.79, P('U5', p)[1]) for p in ag], P('R25', 1))
    s.label('SHUNT_HI', 224.79, 160.02, 'up')
    gnd(P('R25', 4))

    # --- LED output: J2 (LED+), J3 (LED-), D6 free-wheel diode
    heading('LED OUTPUT', 241.3, 45.72)
    s.place('Connector_Generic:Conn_01x01', 'J2', 'LED+ wire', 256.54, 66.04, {'1': 'VLED_UV'}, fp=WIRE_PAD)
    s.place('Connector_Generic:Conn_01x01', 'J3', 'LED- wire', 256.54, 81.28, {'1': 'LED_K'}, fp=WIRE_PAD)
    s.place('Device:D_Schottky', 'D6', 'B340A', 241.3, 73.66, {'1': 'VLED_UV', '2': 'LED_K'}, rot=270,
            fp='Diode_SMD:D_SMA', ref_at=(243.84, 72.39), val_at=(243.84, 74.93))
    rail('VLED_UV', (231.14, 66.04), 'up')
    W((231.14, 66.04), (241.3, 66.04), P('J2', 1))
    W(P('D6', 1), (241.3, 66.04))
    W((219.71, 81.28), (241.3, 81.28), P('J3', 1))
    W(P('D6', 2), (241.3, 81.28))
    s.label('LED_K', 228.6, 81.28, 'up')
    desc('J2/J3: wire pads for the LED cable (~20 AWG) to the LED board J1 (LED+) / J3 (LED-).\n'
         'D6: free-wheeling diode; catches the cable-inductance spike when U5 turns the LED off\n'
         '(iC-HG30 Fig. 6). Place it next to U5 and the pads.', 228.6, 88.9)

    # --- LED current monitor: R25 Kelvin -> R26/R27 -> INA209
    heading('LED CURRENT MONITOR', 238.76, 124.46)
    R('R26', '10R', 238.76, 167.64, 'SHUNT_SP', 'INA_VP', rot=90, ref_at=(236.22, 163.83), val_at=(236.22, 161.29))
    R('R27', '10R', 238.76, 172.72, 'SHUNT_SN', 'INA_VN', rot=90, ref_at=(236.22, 177.8), val_at=(236.22, 180.34))
    W(P('R25', 2), P('R26', 1))
    W(P('R25', 3), P('R27', 1))
    s.place('XFM5050UV:INA209', 'U6', 'INA209AIPWR', 297.18, 160.02,
            {'1': 'INA_VP', '2': 'INA_VN', '3': 'ENABLE_0', '4': 'GND', '5': '3V3_reg', '6': 'GND', '7': NC, '8': NC,
             '9': NC, '10': '3V3_reg', '11': 'GND', '12': 'SCL', '13': 'SDA', '14': '3V3_reg', '15': 'GND', '16': NC},
            fp='Package_SO:TSSOP-16_4.4x5mm_P0.65mm', ref_at=(312.42, 177.8), val_at=(312.42, 180.34))
    C('C20', '100nF', 297.18, 139.7, 'INA_VP', 'INA_VN', rot=90, ref_at=(306.07, 139.7), val_at=(306.07, 142.24))
    W(P('R26', 2), (246.38, 167.64), (246.38, 139.7), (P('U6', 1)[0], 139.7), P('C20', 1))
    W((P('U6', 1)[0], 139.7), P('U6', 1))
    W(P('R27', 2), (251.46, 172.72), (251.46, 134.62), (P('U6', 2)[0], 134.62), (P('U6', 2)[0], 139.7), P('U6', 2))
    W(P('C20', 2), (P('U6', 2)[0], 139.7))
    # supply pins, GND pins
    W(P('U6', 5), (278.13, P('U6', 5)[1]), (278.13, 149.86), (278.13, 147.32))
    W(P('U6', 10), (278.13, P('U6', 10)[1]), (278.13, P('U6', 5)[1]))
    rail('3V3_reg', (278.13, 147.32), 'up')
    W((278.13, 149.86), (269.24, 149.86), (257.81, 149.86))
    cap_to_gnd('C21', '1uF', 269.24, 149.86, '3V3_reg')
    cap_to_gnd('C22', '100nF', 257.81, 149.86, '3V3_reg')
    W(P('U6', 11), (278.13, P('U6', 11)[1]), (278.13, P('U6', 4)[1]), (278.13, 171.45))
    W(P('U6', 4), (278.13, P('U6', 4)[1]))
    gnd((278.13, 171.45))
    s.label('ENABLE_0', *stub(P('U6', 3), 5.08, 0), 'right')
    gnd(stub(P('U6', 6), 5.08, 0), 'right')
    s.label('SCL', *stub(P('U6', 12), 5.08, 0), 'right')
    s.label('SDA', *stub(P('U6', 13), 5.08, 0), 'right')
    rail('3V3_reg', stub(P('U6', 14), 5.08, 0), 'right')
    gnd(stub(P('U6', 15), 5.08, 0), 'right')
    note('U6 INA209 (0x41): LED current on R25 (20 mOhm), +/-80 mV range.\n'
         'Convert = ENABLE_0 (triggered mode syncs to strobes).\n'
         'Route R25 sense leads as a Kelvin pair.', 256.54, 196.85)
    desc('U6 INA209: measures the LED current on R25 and reports it over I2C.\n'
         'R26/R27/C20: low-pass filter on the sense lines.', 256.54, 189.23)

    # --- strobe inverter: HG_EN = NOT ENABLE_0
    heading('STROBE  (ENABLE_0 low = LED on)', 99.06, 147.32)
    s.place('74xGxx:74LVC1G04', 'U7', '74LVC1G04', 139.7, 172.72,
            {'1': NC, '2': 'ENABLE_0', '3': 'GND', '4': 'HG_EN', '5': '3V3_reg'},
            fp='Package_TO_SOT_SMD:SOT-23-5', ref_at=(142.24, 186.69), val_at=(142.24, 189.23))
    W(P('U7', 4), (156.21, 172.72), *[(156.21, P('U5', p)[1]) for p in reversed(en_pins)])
    R('R28', '100k', 156.21, 176.53, 'HG_EN', 'GND')
    gnd(P('R28', 2))
    s.label('HG_EN', 156.21, 152.4, 'left')
    W(P('U7', 5), (134.62, 157.48), (127.0, 157.48), (119.38, 157.48))
    rail('3V3_reg', (127.0, 157.48), 'up')
    cap_to_gnd('C23', '100nF', 119.38, 157.48, '3V3_reg')
    gnd(P('U7', 3))
    R('R29', '100k', 111.76, 168.91, '3V3_reg', 'ENABLE_0')
    rail('3V3_reg', P('R29', 1), 'up')
    W(P('U7', 2), P('R29', 2)[0:1] + (172.72,), (104.14, 172.72))
    W(P('R29', 2), (111.76, 172.72))
    s.label('ENABLE_0', 104.14, 172.72, 'left')
    desc('U7: inverts ENABLE_0 into HG_EN, which drives EN1-4 of U5.\n'
         'R29 holds ENABLE_0 high, so the LED is off by default;\n'
         'R28 holds HG_EN low (LED off) if U7 is unpowered.', 99.06, 193.04)

    # --- power flags and notes
    for i, net in enumerate(['GND', 'VLED_UV', '5V_reg', '3V3_reg']):
        flag(net, 25.4 + i * 20.32, 228.6)
    note('S2 DRIVER (top of stack)\n'
         'U5 iC-HG30: channels 1-4 in parallel, 0.5 A each at 2 A (1 A CW max per channel).\n'
         '  Channels 5-6 unused: CI/EN to GND, LDK open (iC-HG30 Rev B4 p.8).\n'
         '  ~0.8 A/ch max part (3.2 A total), ~0.5 A/ch typ (2.0 A), ~0.3 A/ch min (1.2 A).\n'
         '  Set 2.00 A in firmware by trimming the DAC code to the INA209.\n'
         '  U5 dissipates ~2.5 W at 2 A (up to ~5.7 W with a low-Vf LED).\n'
         'BUS: 1,2 VIN (NC here) | 3,4,12 GND | 5,6 VLED_UV | 7 5V_reg | 8 3V3_reg |\n'
         '  9 SDA | 10 SCL | 11 ENABLE_0\n'
         'UV-C (275 nm) is hazardous to eyes and skin.', 22.86, 236.22)

s.write(os.path.join(D, f'{name}.kicad_sch'))
json.dump({f'{r}|{p}': n for (r, p), n in s.intended.items()},
          open(os.path.join(os.path.dirname(__file__), f'{BOARD}_intended.json'), 'w'))
print('ok', len(s.intended), 'pins')
