{
  "$schema": "./schema/kline.schema.json",
  "spec": "smongrot.kline",
  "spec_version": "1.0.0-phase1",
  "level": 1,
  "status": "stable",
  "summary": "Honda PGM-FI diagnostic K-Line: physical layer, wake, session bring-up, frame format, checksum and echo handling. Level 1 = read-only diagnostics (identity, live data, DTC read).",
  "authority": "Reference implementation (framing, checksum, echo strip, USB session, ECM-ID retry, live pacing). Bench log: Shindengen Lead K2TA, FTDI cable, 2026-10-08.",
  "out_of_scope": [
    "ROM / calibration read",
    "any ECU write, erase, flash, recovery",
    "access or programming procedures of any kind",
    "immobilizer",
    "DTC clear (service 0x60 changes ECU state)"
  ],
  "physical": {
    "bus": "ISO 9141 K-Line, one wire, half-duplex",
    "baud": 10400,
    "data_bits": 8,
    "parity": "none",
    "stop_bits": 1,
    "idle_level": "high (recessive)",
    "echo": "The transceiver (e.g. L9637D, FTDI cables) reads back every byte the tester sends, before the ECU reply. Strip it: see echo_strip.",
    "notes": [
      "macOS FTDI FT232R can do non-standard bauds; level 1 only uses 10400.",
      "Some USB cables echo with bits cleared (never set); see echo_strip.distorted."
    ]
  },
  "wake": {
    "summary": "ISO 9141 wake: hold the line LOW for low_ms, release HIGH, open the UART at 10400 8N1, wait idle_after_ms, then send StartComm.",
    "low_ms": 70,
    "idle_after_ms": 130,
    "before": ["flush/purge RX", "set baud 10400"],
    "must_be_atomic": true,
    "why_atomic": "The LOW width must be a tight 70 ms. Building it from separate remote commands (e.g. two BLE writes) adds tens of ms of jitter and the ECU wakes only sometimes. Time it locally on the adapter (board opcode 0x16, FTDI bit-bang).",
    "transports": {
      "usb_ftdi": "Bit-bang the TXD pin LOW for low_ms, then back to UART at 10400 (bench: Shindengen Lead K2TA answers this on the first try).",
      "usb_emulated": "Fallback for chips without bit-bang: switch to baud round(9000/low_ms) clamped to 200..600, send one 0x00 byte (start + 8 zero bits held low), wait ceil(10000/baud)+60 ms, back to 10400. At 70 ms this gives about 45 ms LOW; Shindengen boxes fresh off key-ON ignore it.",
      "board_ec20_tunnel": "Opcode 0x16 + u16 LE low_ms on the control characteristic (spec/board-ble.json raw_tunnel).",
      "board_klineble": "The SMR board wakes the bus itself (HIGH 100 ms, LOW 70 ms, idle 150 ms) before its own polls; the phone never times it (spec/board-ble.json klineble)."
    }
  },
  "frames": {
    "summary": "Every frame = [header][total length incl. checksum][service][args...][checksum]. Requests from the tester start with 0x72 (diagnostic request) or 0xFE (StartComm); ECU replies start with 0x02.",
    "request": {
      "layout": ["header (0x72)", "L = total bytes including checksum", "service", "args...", "checksum"],
      "table_read": {
        "layout": "72 07 72 <table> <offset> <count> <checksum>",
        "example": "72 07 72 17 00 0F EF",
        "note": "count = number of data bytes asked. Only 0x0000..0x00FF style small reads are level 1 (identity and live tables)."
      }
    },
    "reply": {
      "layout": ["0x02", "L = total bytes including checksum", "service echo (e.g. 0x72, 0x71, 0x74)", "args echo...", "data...", "checksum"],
      "table_read": "02 L 72 <table> <offset> <data...> <checksum>  (5 header bytes)",
      "valid_when": "L >= 4, the frame fits in the buffer, and all L bytes sum to 0 mod 256."
    }
  },
  "checksum": {
    "name": "Honda 8-bit two's complement",
    "compute": "ck = (0x100 - (sum(body) mod 256)) mod 256",
    "equivalent_forms": [
      "((sum & 0xFF) ^ 0xFF) + 1, then & 0xFF",
      "(-sum) & 0xFF"
    ],
    "edge_case": "When sum(body) mod 256 == 0 the checksum is 0x00. The form ((sum & 0xFF) ^ 0xFF) + 1 without the final & 0xFF gives 0x100 there: always mask.",
    "verify": "A frame (body + checksum) is valid when all its bytes sum to 0 mod 256.",
    "not_this": "A plain sum (sum & 0xFF) is WRONG: the ECU ignores such frames (a bug once seen in early firmware, fixed).",
    "worked_example": {
      "body": "72 07 72 17 00 0F",
      "sum": "0x72+0x07+0x72+0x17+0x00+0x0F = 0x111",
      "sum_mod_256": "0x11",
      "xor_ff": "0xEE",
      "plus_1": "0xEF",
      "frame": "72 07 72 17 00 0F EF"
    }
  },
  "echo_strip": {
    "summary": "Applied to every raw read-back of one request (reference implementation). T = the exact request bytes, RAW = everything read back for it.",
    "rules": [
      "exact: if RAW starts with T → echo = true, reply = RAW[len(T):] (even when what follows is not a valid frame or is empty).",
      "distorted: else if len(RAW) > len(T), every one of the first len(T) bytes only CLEARS bits of T ((RAW[i] & ~T[i]) == 0), and a valid reply frame starts at RAW[len(T)] → unless a valid frame starting at RAW[0] is LONGER than len(T), echo = true, distorted = true, reply = RAW[len(T):].",
      "otherwise: echo = false, reply = RAW unchanged (the reply is never cut on position alone)."
    ],
    "valid_reply_at": "valid frame at position p: p+2 <= len(RAW), L = RAW[p+1] >= 4, p+L <= len(RAW), RAW[p..p+L-1] sums to 0 mod 256. Its length is L.",
    "distorted_note": "Field: some USB cables echo with bits cleared. Counted once per session for telemetry; no other behaviour change.",
    "level2_note": "The app also accepts one fixed-length level-2 reply form in valid_reply_at; it never occurs in level-1 traffic and is not part of this spec."
  },
  "session": {
    "summary": "Bring-up order used by the reference USB path (and by the EC20 raw tunnel). Bench trace: Shindengen Lead K2TA, FTDI cable, 2026-10-08.",
    "steps": [
      {
        "id": "wake",
        "do": "wake (see wake)",
        "retry": "wake + start_comm + liveness together up to 4 attempts (kConnectWakeTries) before 'ECU silent'."
      },
      {
        "id": "start_comm",
        "request": "FE 04 72 8C",
        "expect_reply": false,
        "note": "Reply not required: on the Shindengen bench only the echo came back."
      },
      {
        "id": "liveness",
        "do": "Send each in order; the first with a non-empty echo-stripped reply = session up. None answered = no bike / key off → next wake attempt.",
        "requests": [
          {"name": "ecm_query", "request": "72 05 00 F0 99", "bench_reply": "02 04 00 FA"},
          {"name": "start_diag", "request": "72 05 71 00 18"},
          {"name": "alt_keepalive", "request": "7E 06 01 01 00 7A", "note": "Some Keihin V850 boxes (Giorno/Lead) answer only this. Reproduced for parity with the app; it is a status poll, not a write."}
        ]
      },
      {
        "id": "start_diag",
        "request": "72 05 71 00 18",
        "reply": "02 0F 71 00 <5-byte ECM-ID> <5 bytes> <ck>",
        "bench_reply": "02 0F 71 00 01 04 78 0D 01 EE 00 00 00 00 05",
        "required": "Yes. Without it StartComm succeeds but the live tables stay silent (bench 2026-09-14)."
      },
      {
        "id": "ecm_id",
        "request": "72 07 72 00 00 05 10",
        "reply": "02 0B 72 00 00 <5-byte ECM-ID> <ck>",
        "bench_reply": "02 0B 72 00 00 01 04 78 0D 01 F6",
        "retry": {"tries": 3, "gap_ms": 300, "why": "The first ID read right after StartDiag can come back empty."},
        "fallback": "If no valid ID frame: use the ECM-ID from this session's StartDiag reply.",
        "format": "10 upper-case hex chars, e.g. 0104780D01"
      },
      {
        "id": "live",
        "do": "Detect the profile and poll (spec/live.json)."
      }
    ],
    "ecm_id_extraction": {
      "summary": "ECM-ID bytes over an echo-stripped reply.",
      "rules": [
        "Prefer the FIRST position i (scanning forward) where RAW[i..] = 02 0B 72 00 00 and RAW[i..i+10] sums to 0 mod 256: ID = RAW[i+5..i+9].",
        "Else the FIRST position where RAW[i..] = 02 0F 71 00 and RAW[i..i+14] sums to 0 mod 256: ID = RAW[i+4..i+8].",
        "Else no ID (never a slice taken by position)."
      ]
    }
  },
  "timing": {
    "command_quiet_ms": 120,
    "command_timeout_ms": 2000,
    "table_read_quiet_ms": 120,
    "table_read_timeout_ms": 500,
    "dtc_gap_ms": 60,
    "live_min_gap_ms": 60,
    "note": "A read ends after quiet_ms of RX silence (the window restarts on every received chunk and starts right after the write) or at timeout_ms. Values are what the app uses, not ECU limits."
  }
}
