#!/usr/bin/env python3
"""Linux port of "KC868 Controller Bootloader.exe" (Kincony ARM CPU IAP tool).

Protocol reproduced byte-for-byte from the decompiled .NET tool:
  enter bootloader : 7E 7E 5A 00 B4 42
  run application  : 7E 7E 5A 02 75 C3
  data packet      : 7E 7E 5A 01 <idx hi lo> <count hi lo> <1024 data> <crc hi lo>
                     CRC16/MODBUS over the first 1032 bytes, sent high byte first.
                     Last (partial) packet is zero padded. The original tool sends it as
                     1035 bytes (one extra 0x00); that hung the bootloader every time on
                     2026-10-17, so this script sends 1034 by default (--pad-last restores
                     the vendor behaviour).
  device ACK       : 2B 4F 4B CF 75   ("+OK" + crc)
  device NAK       : 2D 45 52 52 00 A4 ("-ERR" ...)

Usage:
  kc_flash.py --dry-run FIRMWARE.bin
  kc_flash.py --port /dev/ttyUSB0 --window 300 FIRMWARE.bin

N30 notes:
  - Connect a USB-RS485 adapter to the N30 RS485 A/B terminals (USB-C only reaches the ESP32).
  - Start the script, then cut and restore the N30's hard-wired power supply. Tapping RST does
    not enter the bootloader (and holding RST 3 s factory-resets the ARM CPU).
  - Hold the ESP32's BOOT/DL button while power comes back (release after ~2 s). That parks
    the ESP32 in its ROM download mode so its Modbus polling can't disturb the ARM bootloader.
  - If a flash is left incomplete, the bootloader stays resident: re-running the script then
    connects immediately, no power cycle needed.
  - After flashing, energy can be cleared with coils 520/521/522 (buttons in n30.yaml).
"""
import argparse
import sys
import time

BOOT_CMD = bytes([126, 126, 90, 0, 180, 66])
APP_CMD = bytes([126, 126, 90, 2, 117, 195])
ACK = bytes([43, 79, 75, 207, 117])
NAK = bytes([45, 69, 82, 82, 0, 164])
BAUD = 38400
RETRIES = 5
TIMEOUT = 5.0  # tool's timer1 interval


def crc16_modbus(data: bytes) -> int:
    crc = 0xFFFF
    for b in data:
        crc ^= b
        for _ in range(8):
            crc = (crc >> 1) ^ 0xA001 if crc & 1 else crc >> 1
    return crc


def build_packets(fw: bytes, pad_last: bool = False) -> list[bytes]:
    full, rem = divmod(len(fw), 1024)
    count = full + (1 if rem else 0)
    packets = []
    for idx in range(count):
        chunk = fw[idx * 1024:(idx + 1) * 1024]
        body = bytearray(1032)
        body[0:4] = b"\x7e\x7e\x5a\x01"
        body[4:6] = idx.to_bytes(2, "big")
        body[6:8] = count.to_bytes(2, "big")
        body[8:8 + len(chunk)] = chunk
        crc = crc16_modbus(body)
        pkt = bytes(body) + crc.to_bytes(2, "big")
        if len(chunk) < 1024 and pad_last:
            pkt += b"\x00"  # original tool sends the short packet as 1035 bytes
        packets.append(pkt)
    return packets


def wait_reply(ser, timeout=TIMEOUT, raw=None):
    """Return 'ack', 'nak' or None (timeout). Scans the stream for either frame.
    If raw is a bytearray, every received byte is appended to it (for debugging)."""
    buf = bytearray()
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        b = ser.read(1)
        if not b:
            continue
        if raw is not None:
            raw += b
        buf += b
        if buf.endswith(ACK):
            return "ack"
        if buf.endswith(NAK):
            return "nak"
        del buf[:-8]
    return None


T0 = time.monotonic()


def log(msg):
    print(f"[{time.monotonic() - T0:7.2f}s] {msg}")


def ping(ser):
    """Send one detect frame and report whether the bootloader still answers.
    Only call between packets, never while the bootloader is mid-frame."""
    ser.reset_input_buffer()
    ser.write(BOOT_CMD)
    raw = bytearray()
    r = wait_reply(ser, 1.0, raw=raw)
    log(f"ping: {r or 'no reply'}  rx={raw.hex(' ') or '(nothing)'}")
    return r == "ack"


def enter_bootloader(ser, window, bauds, settle):
    print(f"Sending bootloader-detect every 100 ms for {window:.0f} s, alternating baud {bauds}.")
    print(">>> NOW disconnect and reconnect the N30's power supply (tapping RST may not work). <<<")
    deadline = time.monotonic() + window
    i = 0
    while time.monotonic() < deadline:
        ser.baudrate = bauds[i % len(bauds)]
        i += 1
        ser.reset_input_buffer()
        ser.write(BOOT_CMD)
        r = wait_reply(ser, 0.1)
        if r == "ack":
            log(f"goto bootloader ok at {ser.baudrate} baud")
            if settle:
                log(f"waiting {settle:.1f} s before sending data")
                time.sleep(settle)
            ser.reset_input_buffer()
            return True
        if r == "nak":
            print(f"bootloader replied ERR at {ser.baudrate}, retrying")
    return False


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("firmware")
    ap.add_argument("--port")
    ap.add_argument("--dry-run", action="store_true")
    ap.add_argument("--window", type=float, default=300.0, help="seconds to keep trying bootloader detect")
    ap.add_argument("--no-run", action="store_true", help="don't send the run-application command at the end")
    # 38400 only by default: detect frames sent at other rates arrive as garbage and can
    # leave the bootloader's packet framing misaligned (every packet then times out).
    ap.add_argument("--bauds", default="38400", help="comma list of baud rates to try for bootloader detect")
    ap.add_argument("--gap", type=float, default=0.1, help="seconds to pause after each ACK before the next packet")
    ap.add_argument("--settle", type=float, default=0.0, help="seconds to stay silent after the bootloader ACKs detect")
    ap.add_argument("--timeout", type=float, default=15.0, help="seconds to wait for each packet's ACK")
    ap.add_argument("--first-timeout", type=float, default=60.0, help="seconds to wait for packet 0's ACK")
    ap.add_argument("--pad-last", action="store_true",
                    help="send the final short packet as 1035 bytes like the vendor tool (hung the bootloader here)")
    ap.add_argument("--no-ping", action="store_true", help="don't ping the bootloader before packet 0 / after a timeout")
    args = ap.parse_args()

    fw = open(args.firmware, "rb").read()
    packets = build_packets(fw, args.pad_last)
    print(f"firmware {len(fw)} bytes -> {len(packets)} packets")

    if args.dry_run:
        for i, p in enumerate(packets):
            print(f"  pkt {i:2d}: len={len(p)} hdr={p[:8].hex(' ')} crc={p[1032:1034].hex(' ')}")
        return 0

    if not args.port:
        ap.error("--port required unless --dry-run")
    import serial

    bauds = [int(b) for b in args.bauds.split(",")]
    with serial.Serial(args.port, bauds[0], bytesize=8, parity="N", stopbits=1, timeout=0.05) as ser:
        if not enter_bootloader(ser, args.window, bauds, args.settle):
            print("No bootloader response. Check A/B wiring, adapter, and RST timing.")
            return 1
        if not args.no_ping and not ping(ser):
            log("Bootloader stopped answering right after detect.")
            return 1

        for i, pkt in enumerate(packets):
            for attempt in range(1, RETRIES + 1):
                ser.reset_input_buffer()
                ser.write(pkt)
                raw = bytearray()
                # Generous timeouts: resending or pinging before a late ACK arrives would
                # desync the bootloader. Packet 0 normally ACKs in ~0.3 s.
                r = wait_reply(ser, args.first_timeout if i == 0 else args.timeout, raw=raw)
                if r == "ack":
                    log(f"Download {i + 1}K  progress {i + 1}/{len(packets)}"
                        + (f"  (attempt {attempt})" if attempt > 1 else ""))
                    time.sleep(args.gap)
                    break
                log(f"packet {i}: {'ERR' if r == 'nak' else 'timeout'} (attempt {attempt}/{RETRIES})"
                    f"  rx={raw.hex(' ') or '(nothing)'}")
                if not args.no_ping and not ping(ser):
                    log("Bootloader no longer answers; power-cycle the board and re-run.")
                    return 1
            else:
                log("Download failed. Power-cycle the board and re-run this script.")
                return 1

        log("Data send complete")
        if args.no_run:
            return 0
        ser.reset_input_buffer()
        ser.write(APP_CMD)
        r = wait_reply(ser)
        log("Download finished begin running" if r == "ack" else f"run command reply: {r}")
    return 0


if __name__ == "__main__":
    sys.exit(main())
