#!/usr/bin/env python3
"""Generate the SimulIDE 1.1.0 circuit used to test parking_radar.ino.

Arduino Uno + HC-SR04 (TRIG D8, ECHO D9) + buzzer (D3) + LEDs (D5 green, D6 yellow,
D7 red, each through 220 ohm), a logic analyzer on D3/D8/D9 and, optionally,
a SerialPort component bridged to a Linux pty so the sketch's serial output can be
saved as a text log.

Wires that go to more than one place use SimulIDE "Tunnel" parts: tunnels with
the same name are electrically connected (e.g. every tunnel named D8).

SimulIDE's HC-SR04 model takes distance as a voltage on its "Dist." pin,
1 V = 1 m (SimulIDE component list), so 0.300 V means 30 cm.

Usage: make_circuit.py VOLTS OUT.sim1 FIRMWARE.hex [PTY_PATH|-] [normal|swap|noecho]
"""
import sys

UNO_PIN_Y = {"0": 16, "1": 24, "3": 40, "5": 56, "6": 64, "7": 72, "8": 88, "9": 96}


def uno_pin(p):
    return (8, UNO_PIN_Y[p])


def pts(*p):
    return ",".join(f"{x},{y}" for x, y in p)


def conn(uid, a, b, points):
    return f'<item itemtype="Connector" uid="{uid}" startpinid="{a}" endpinid="{b}" pointList="{pts(*points)}" />'


def tunnel(cid, name, pos, hflip):
    return (f'<item itemtype="Tunnel" CircId="{cid}" mainComp="false" Show_id="false" Show_Val="false" '
            f'Pos="{pos[0]},{pos[1]}" rotation="0" hflip="{hflip}" vflip="1" label="{cid}" idLabPos="-16,-24" '
            f'labelrot="0" valLabPos="-16,20" valLabRot="0" Name="{name}" IsBus="false" />')


def ground(cid, pin_pos):
    x, y = pin_pos
    return (f'<item itemtype="Ground" CircId="{cid}" mainComp="false" Show_id="false" Show_Val="false" '
            f'Pos="{x},{y + 16}" rotation="0" hflip="1" vflip="1" label="{cid}" idLabPos="-16,8" labelrot="0" '
            f'valLabPos="-16,20" valLabRot="0" />')


def circuit(dist_volt, hex_name, port=None, variant="normal"):
    I = ['<circuit version="" rev="2224" stepSize="1000000" stepsPS="1000000" NLsteps="100000" reaStep="1000000" animate="1" >']
    I.append('<item itemtype="Subcircuit" CircId="Uno-2" mainComp="false" Show_id="true" Show_Val="false" Pos="0,0" '
             'rotation="0" hflip="1" vflip="1" label="Arduino Uno" idLabPos="50,-17" labelrot="0" valLabPos="0,0" '
             'valLabRot="0" Logic_Symbol="false">\n'
             f'<mainCompProps MainCompId="mega328-109" Frequency="16 MHz" Program="{hex_name}" Auto_Load="false" '
             'saveEepr="true" SerialMon="1" />\n</item>')

    # Shared Uno pins go out through tunnels.
    shared = ["3", "8", "9"] + (["0", "1"] if port else [])
    for p in shared:
        x, y = uno_pin(p)
        I.append(tunnel(f"Tunnel-U{p}", f"D{p}", (-16, y), -1))
        I.append(conn(f"C-u{p}", f"Uno-2-{p}", f"Tunnel-U{p}-pin", [(x, y), (-16, y)]))

    # HC-SR04, mirrored, upper left. Pin offsets (hflip=-1): trig (0,48), echo (-8,48), Dist (88,-24)
    sx, sy = -200, -150
    trig, echo, dist = (sx, sy + 48), (sx - 8, sy + 48), (sx + 88, sy - 24)
    I.append(f'<item itemtype="SR04" CircId="SR04-3" mainComp="false" Show_id="true" Show_Val="false" Pos="{sx},{sy}" '
             'rotation="0" hflip="-1" vflip="1" label="HC-SR04" idLabPos="-16,-24" labelrot="0" valLabPos="0,0" valLabRot="0" />')
    # variant: "normal" (TRIG->D8, ECHO->D9), "swap" (TRIG->D9, ECHO->D8: wired the wrong way round),
    #          "noecho" (ECHO wire left unconnected)
    trig_net, echo_net = ("D9", "D8") if variant == "swap" else ("D8", "D9")
    I.append(tunnel("Tunnel-S8", trig_net, (sx + 40, sy + 68), 1))
    I.append(conn("C-trig", "SR04-3-trigpin", "Tunnel-S8-pin", [trig, (sx, sy + 68), (sx + 40, sy + 68)]))
    if variant != "noecho":
        I.append(tunnel("Tunnel-S9", echo_net, (sx + 40, sy + 84), 1))
        I.append(conn("C-echo", "SR04-3-outpin", "Tunnel-S9-pin", [echo, (sx - 8, sy + 84), (sx + 40, sy + 84)]))
    vs = (dist[0] + 60, dist[1] - 16)  # voltage source, hflip=-1: outPin at (-28,16)
    vout = (vs[0] - 28, vs[1] + 16)
    I.append(f'<item itemtype="Voltage Source" CircId="Voltage Source-1" mainComp="false" ShowProp="Value_Volt" '
             f'Show_id="true" Show_Val="true" Pos="{vs[0]},{vs[1]}" rotation="0" hflip="-1" vflip="1" '
             'label="Dist (1V = 1m)" idLabPos="-16,-24" labelrot="0" valLabPos="-4,33" valLabRot="0" Running="true" '
             f'Value_Volt="{dist_volt:.3f} V" MaxValue="5 V" MinValue="0 V" />')
    I.append(conn("C-dist", "Voltage Source-1-outPin", "SR04-3-inpin", [vout, dist]))

    # Buzzer (AudioOut in buzzer mode), left middle. hflip=-1: lPin (16,-8), rPin (16,0)
    bx, by = -260, 56
    bl, br = (bx + 16, by - 8), (bx + 16, by)
    I.append(f'<item itemtype="AudioOut" CircId="Audio Out-20" mainComp="false" Show_id="true" Show_Val="false" '
             f'Pos="{bx},{by}" rotation="0" hflip="-1" vflip="1" label="Buzzer" idLabPos="-12,-24" labelrot="0" '
             'valLabPos="0,0" valLabRot="0" Buzzer="true" Impedance="8 Ω" />')
    I.append(tunnel("Tunnel-B3", "D3", (bx + 48, by - 8), 1))
    I.append(conn("C-bz1", "Audio Out-20-lPin", "Tunnel-B3-pin", [bl, (bx + 48, by - 8)]))
    g = (bx + 32, by + 16)
    I.append(ground("Ground-20", g))
    I.append(conn("C-bz2", "Audio Out-20-rPin", "Ground-20-Gnd", [br, (g[0], br[1]), g]))

    # LEDs: Uno pin -> 220R -> LED anode (lPin); cathode (rPin) -> GND. LED rotated 180 so anode faces right.
    for k, (color, pin) in enumerate([("Green", "5"), ("Yellow", "6"), ("Red", "7")]):
        n = 10 + k
        px, py = uno_pin(pin)
        yy = 170 + 40 * k
        lane = -24 - 16 * k
        rx, lx = -90, -160
        gp = (lx - 40, yy + 8)
        I.append(f'<item itemtype="Resistor" CircId="Resistor-{n}" mainComp="false" ShowProp="Resistance" Show_id="false" '
                 f'Show_Val="true" Pos="{rx},{yy}" rotation="0" hflip="1" vflip="1" label="R{n}" idLabPos="-12,-20" '
                 'labelrot="0" valLabPos="-11,-15" valLabRot="0" Resistance="220 Ω" />')
        I.append(f'<item itemtype="Led" CircId="Led-{n}" mainComp="false" Show_id="true" Show_Val="false" Pos="{lx},{yy}" '
                 f'rotation="180" hflip="1" vflip="1" label="D{pin} {color}" idLabPos="16,24" labelrot="180" valLabPos="0,0" '
                 f'valLabRot="0" Color="{color}" Grounded="false" Threshold="2.4 V" MaxCurrent="0.03 A" Resistance="0.6 Ω" />')
        I.append(ground(f"Ground-{n}", gp))
        I.append(conn(f"C-l{n}a", f"Uno-2-{pin}", f"Resistor-{n}-rPin", [(px, py), (lane, py), (lane, yy), (rx + 16, yy)]))
        I.append(conn(f"C-l{n}b", f"Resistor-{n}-lPin", f"Led-{n}-lPin", [(rx - 16, yy), (lx + 16, yy)]))
        I.append(conn(f"C-l{n}c", f"Led-{n}-rPin", f"Ground-{n}-Gnd", [(lx - 16, yy), (gp[0], yy), gp]))

    # Logic analyzer, right of the board. Pin k at (-88, -64 + 16k).
    lax, lay = 520, 60
    I.append(f'<item itemtype="LAnalizer" CircId="LAnalizer-30" mainComp="false" Show_id="false" Show_Val="false" '
             f'Pos="{lax},{lay}" rotation="0" hflip="1" vflip="1" label="Logic Analyzer" idLabPos="-90,-100" labelrot="0" '
             'valLabPos="-16,20" valLabRot="0" Basic_X="300 Pixels" Basic_Y="135 _px" BufferSize="100000" connectGnd="true" '
             'InputImped="1e+07 Ω" TimDiv="200000000000" TimPos="0" VolDiv="0.15" Tunnels="D3,D8,D9,,,,,," Trigger="8" '
             'TimeStep="1000 _ps" AutoExport="false" TresholdR="2.5 V" Bus="false,false,false,false,false,false,false,false," '
             'TresholdF="2.5 V" />')
    for ch, p in enumerate(["3", "8", "9"]):
        a = (lax - 88, lay - 64 + 16 * ch)
        I.append(tunnel(f"Tunnel-A{p}", f"D{p}", (a[0] - 24, a[1]), -1))
        I.append(conn(f"C-a{p}", f"LAnalizer-30-Pin{ch}", f"Tunnel-A{p}-pin", [a, (a[0] - 24, a[1])]))

    if port:
        spx, spy = -200, -20  # SerialPort: pin0 (-40,-8), pin1 (-40,8)
        I.append(f'<item itemtype="SerialPort" CircId="SerialPort-40" mainComp="false" Show_id="true" Show_Val="false" '
                 f'Pos="{spx},{spy}" rotation="0" hflip="1" vflip="1" label="SerialPort (pty)" idLabPos="14,-32" labelrot="0" '
                 f'valLabPos="-16,20" valLabRot="0" Auto="true" Port="{port}" Baudrate="9600 _Bauds" DataBits="8 _Bits" '
                 'StopBits="1 _Bits" SerialMon="false" />')
        for k, p in enumerate(["0", "1"]):
            a = (spx - 40, spy - 8 + 16 * k)
            I.append(tunnel(f"Tunnel-P{p}", f"D{p}", (a[0] - 24, a[1]), -1))
            I.append(conn(f"C-p{p}", f"SerialPort-40-pin{k}", f"Tunnel-P{p}-pin", [a, (a[0] - 24, a[1])]))
    I.append('</circuit>')
    return "\n\n".join(I) + "\n"


if __name__ == "__main__":
    volt = float(sys.argv[1]); out = sys.argv[2]; hexn = sys.argv[3]
    port = sys.argv[4] if len(sys.argv) > 4 and sys.argv[4] != "-" else None
    variant = sys.argv[5] if len(sys.argv) > 5 else "normal"
    open(out, "w", encoding="utf-8").write(circuit(volt, hexn, port, variant))
