LeaperkimSyncProtocol.kt

/*
 *
 *  Copyright (C) 2026 Gauthier Le Bartz Lyan (Tritbool)
 *  euc_ble_library — version 1.2.0 — licence GPL-3.0
 *  https://github.com/Tritbool/euc_ble_library
 * /
 */

package io.github.tritbool.euc.ble.protocols

import io.github.tritbool.euc.ble.core.BLEConstants
import io.github.tritbool.euc.ble.core.ByteUtils
import io.github.tritbool.euc.ble.core.EucCrc32
import io.github.tritbool.euc.ble.core.EucClock
import io.github.tritbool.euc.ble.core.EucDateTime
import io.github.tritbool.euc.ble.frames.ByteByByteFrameParser
import io.github.tritbool.euc.ble.models.BMSData
import io.github.tritbool.euc.ble.models.DiagnosticLogTransfer
import io.github.tritbool.euc.ble.models.EUCData
import io.github.tritbool.euc.ble.models.resolveBmsChargingState
import io.github.tritbool.euc.ble.core.EucUuid as UUID
import kotlin.math.abs
import kotlin.math.roundToInt

/**
 * Leaperkim/Veteran protocol implementation based on WheelLog raw frame behavior.
 *
 * Stream framing:
 * - Header: DC 5A 5C
 * - Byte 3: frame length marker (len)
 * - Full frame size: len + 4 bytes
 * - For long frames (len > 38), trailing CRC32 is expected
 */
open class LeaperkimSyncProtocol(private val clock: EucClock) : SyncEucProtocol {
    override fun hasSpeedMeasurement(data: EUCData): Boolean = true

    companion object {
        private const val LEAPERKIM_MAX_BMS_CELLS = 42
        private val LKAP = byteArrayOf(0x4C, 0x6B, 0x41, 0x70)  // "LkAp"
        private val LDAP = byteArrayOf(0x4C, 0x64, 0x41, 0x70)  // "LdAp"
    }

    override val manufacturer: String = "Leaperkim"
    override val protocolId: String = "LeaperkimProtocol"
    override val supportedCommandTypes: Set<CommandType>
        get() = CommandCatalogue.supportedTypes(getCommandDescriptors())

    override fun matchesDeviceName(deviceName: String): Boolean {
        val lower = deviceName.lowercase()
        // Veteran/Leaperkim wheels often advertise a generic "LK" + digits BLE name
        // (e.g. "LK13709" on a Lynx) instead of the model name.
        val lkSerialName = lower.length > 2 && lower.startsWith("lk") && lower[2].isDigit()
        return lkSerialName || lower.contains("veteran") || lower.contains("leaperkim") ||
                lower.contains("sherman") || lower.contains("lynx") ||
                lower.contains("patton") || lower.contains("oryx") || lower.contains("abrams")
    }

    override fun getServiceUUID(): UUID = UUID.fromString(BLEConstants.LEAPERKIM_SERVICE_UUID)
    override fun getDataCharacteristicUUID(): UUID =
        UUID.fromString(BLEConstants.LEAPERKIM_READ_CHARACTERISTIC)

    override fun getWriteCharacteristicUUID(): UUID =
        UUID.fromString(BLEConstants.LEAPERKIM_WRITE_CHARACTERISTIC)

    /**
     * Veteran/LeaperKim wheels share the Gotway-style FFE1 serial-to-BLE bridge, which only accepts
     * write-without-response; legacy WheelLog also uses WriteType.WITHOUT_RESPONSE for them.
     */
    override val preferredWriteType: ProtocolWriteType = ProtocolWriteType.NO_RESPONSE

    private enum class ParseState {
        UNKNOWN,
        LENGTH_SEARCH,
        COLLECTING
    }

    private var parseState: ParseState = ParseState.UNKNOWN
    private var old1: Int = 0
    private var old2: Int = 0
    private var expectedLen: Int = 0
    private val streamBuffer = ArrayList<Byte>()

    private val unpacker: (Byte) -> List<ByteArray> = unpacker@{ next ->
        val out = mutableListOf<ByteArray>()
        val c = next.toInt() and 0xFF
        when (parseState) {
            ParseState.COLLECTING -> {
                val currentSize = streamBuffer.size
                if ((currentSize == 22 && c != 0x00) ||
                    (currentSize == 30 && c != 0x00 && c != 0x07) ||
                    (currentSize == 23 && (c and 0xFE) != 0x00)
                ) {
                    resetUnpacker()
                    return@unpacker out
                }
                streamBuffer.add(c.toByte())
                if (currentSize == expectedLen + 3) {
                    out.add(streamBuffer.toByteArray())
                    resetUnpacker()
                }
            }

            ParseState.LENGTH_SEARCH -> {
                streamBuffer.add(c.toByte())
                expectedLen = c
                parseState = ParseState.COLLECTING
                old2 = old1
                old1 = c
            }

            ParseState.UNKNOWN -> {
                if (c == 0x5C && old1 == 0x5A && old2 == 0xDC) {
                    streamBuffer.clear()
                    streamBuffer.add(0xDC.toByte())
                    streamBuffer.add(0x5A.toByte())
                    streamBuffer.add(0x5C.toByte())
                    parseState = ParseState.LENGTH_SEARCH
                } else if (c == 0x5A && old1 == 0xDC) {
                    old2 = old1
                } else {
                    old2 = 0
                }
                old1 = c
            }
        }
        out
    }

    private fun resetUnpacker() {
        old1 = 0
        old2 = 0
        expectedLen = 0
        parseState = ParseState.UNKNOWN
        streamBuffer.clear()
    }

    var debugFramesObserved: Int = 0
        private set

    var debugFramesParsed: Int = 0
        private set

    var debugFramesSent: Int = 0
        private set

    var debugSendFailures: Int = 0
        private set

    private val frameParser = ByteByByteFrameParser(unpacker, resetUnpacker = { resetUnpacker() })
    private val outbox = ProtocolOutbox()
    private var sessionStartTimestampMs: Long? = null

    private var lastMajorVersion: Int? = null
    // Last Oryx BMS state-of-charge from a page-2 sub-frame (frame[50]).
    // Cached and stamped onto every EUCData so battery doesn't flicker back to the
    // voltage-curve estimate on the other 8 pages (mVer 8 / Oryx only).
    private var lastOryxBatterySoc: Int = -1

    // Last charge mode reported by the wheel (frame byte 22, 0 = not charging).
    private var lastKnownChargeMode: Int? = null
    private val bmsCellPages: MutableMap<Int, DoubleArray> = mutableMapOf()
    private val bmsTemperatures: MutableMap<Int, List<Double>> = mutableMapOf()
    private val bmsCurrents: MutableMap<Int, Double> = mutableMapOf()
    private val diagnosticLog = LeaperkimDiagnosticLogDownload(outbox)
    private var lastKnownTiltBackSpeed: Int? = null
    private var lastKnownAlarmSpeed: Int? = null
    private var lastKnownMosfetTemperature: Double? = null

    override fun onNotification(data: ByteArray) {
        if (data.isEmpty()) return
        updateLastKnownVersionFromRawChunk(data)
        frameParser.appendAndExtract(data).forEach(::processFrame)
    }

    override fun pollOutput(): ProtocolOutput? = outbox.poll()

    override fun onTimer(id: String) {
        diagnosticLog.onTimer(id)
    }

    override fun getDiagnosticLogTransfer(): DiagnosticLogTransfer? = diagnosticLog.snapshot()

    override fun commandStateError(commandId: String): String? = when {
        commandId == CommandType.SET_SPEED_LIMIT.name && lastKnownTiltBackSpeed == null ->
            "Wheel tiltback settings must be received before changing the speed limit"
        commandId == CommandType.SET_ALARM_SPEED.name && lastKnownAlarmSpeed == null ->
            "Wheel alarm settings must be received before changing the alarm speed"
        else -> null
    }

    private fun updateLastKnownVersionFromRawChunk(data: ByteArray) {
        if (data.size < 30) return
        if (data[0] != 0xDC.toByte() || data[1] != 0x5A.toByte() || data[2] != 0x5C.toByte()) return

        val len = ByteUtils.getUnsignedByte(data, 3)
        if (data.size != len + 4) return
        // WheelLog-compatible Leaperkim frames longer than 38 bytes carry trailing CRC32.
        if (len > 38 && !isCrcValid(data, len)) return

        val versionRaw = ByteUtils.tryGetUnsignedShortBE(data, 28) ?: return
        if (versionRaw > 0) {
            lastMajorVersion = extractMajorVersion(versionRaw)
        }
    }

    private fun processFrame(frame: ByteArray) {
        debugFramesObserved++
        if (frame.size < 4) return
        val len = ByteUtils.getUnsignedByte(frame, 3)
        if (frame.size != len + 4 || (len > 38 && !isCrcValid(frame, len))) return
        // Smart-BMS equipped wheels (Lynx S, Patton, Oryx) cycle through four frame layouts.
        // Frames with LEN == 0x5F carry BMS ADC readings at bytes 4..5, NOT pack voltage.
        // Parsing them as regular telemetry produces ~3–7 V voltage spikes every ~200 ms.
        // The event-log download reuses the same stream: log pages replace the frame
        // extension (byte 46 and beyond) while the main telemetry body keeps updating.
        if (diagnosticLog.isActive && frame.size > 46) diagnosticLog.onFrame(frame)
        // Skip the telemetry parse and only extract BMS cell data from these frames.
        if (frame.size > 3 && frame[3] == 0x5F.toByte()) {
            if (frame.size >= 47) parseSmartBms(frame)
            return
        }
        val parsed = parseFrame(frame)
        if (parsed != null) {
            debugFramesParsed++
            outbox.push(ProtocolOutput.Telemetry(parsed))
            debugFramesSent++
        }
    }

    private fun parseFrame(frame: ByteArray): EUCData? {
        if (frame.size < 36) return null
        if (frame[0] != 0xDC.toByte() || frame[1] != 0x5A.toByte() || frame[2] != 0x5C.toByte()) return null

        val len = ByteUtils.getUnsignedByte(frame, 3)
        if (frame.size != len + 4) return null
        // WheelLog-compatible Leaperkim frames longer than 38 bytes carry trailing CRC32.
        if (len > 38 && !isCrcValid(frame, len)) return null

        val voltageRaw = ByteUtils.tryGetUnsignedShortBE(frame, 4) ?: return null
        val speedRaw = ByteUtils.tryGetSignedShortBE(frame, 6) ?: return null
        val currentRaw = ByteUtils.tryGetSignedShortBE(frame, 16) ?: return null
        val tempRaw = ByteUtils.tryGetSignedShortBE(frame, 18) ?: return null
        val angleRaw = ByteUtils.tryGetSignedShortBE(frame, 32)
        val pwmRaw = ByteUtils.tryGetUnsignedShortBE(frame, 34) ?: 0
        val chargeMode = ByteUtils.tryGetUnsignedShortBE(frame, 22) ?: 0
        lastKnownChargeMode = chargeMode
        val autoOffSeconds = ByteUtils.tryGetUnsignedShortBE(frame, 20) ?: 0
        val speedAlertRaw = ByteUtils.tryGetUnsignedShortBE(frame, 24) ?: 0
        val speedTiltBackRaw = ByteUtils.tryGetUnsignedShortBE(frame, 26) ?: 0
        lastKnownTiltBackSpeed = speedTiltBackRaw
        lastKnownAlarmSpeed = speedAlertRaw
        val pedalsMode = ByteUtils.tryGetUnsignedShortBE(frame, 30)
        val versionRaw = ByteUtils.tryGetUnsignedShortBE(frame, 28) ?: 0

        val voltage = voltageRaw / 100.0
        val speed = decodeSpeed(speedRaw)
        val current = currentRaw / 100.0
        val temperature = tempRaw / 100.0
        val pwm = pwmRaw / 100.0
        val angle = angleRaw?.let { it / 100.0 }

        if (voltage !in 20.0..180.0) return null
        if (speed !in -120.0..120.0) return null
        if (current !in -300.0..300.0) return null
        if (temperature !in -50.0..130.0) return null

        val majorVersion = extractMajorVersion(versionRaw)
        lastMajorVersion = majorVersion
        if (majorVersion >= 5) {
            parseSmartBms(frame)
        }
        // Oryx (mVer 8) carries its own BMS state-of-charge at byte 50 of page-2 sub-frames
        // (page identifier at byte 46, cycling 0..8). Cache it and stamp onto every frame so
        // battery stays steady between page-2 frames instead of flickering to the voltage curve.
        val pageId = if (frame.size >= 47) ByteUtils.getUnsignedByte(frame, 46) else -1
        if (majorVersion == 8 && pageId == 2 && frame.size >= 51) {
            val soc = ByteUtils.getUnsignedByte(frame, 50)
            if (soc in 0..100) lastOryxBatterySoc = soc
        }
        val model = modelByMajorVersion(majorVersion)
        val battery = if (majorVersion == 8 && lastOryxBatterySoc in 0..100) {
            lastOryxBatterySoc
        } else {
            estimateBatteryPercent(voltageRaw, majorVersion)
        }

        val tripDistanceKm = decodeDistanceKm(frame, 8)
        val totalDistanceKm = decodeDistanceKm(frame, 12)
        val now = clock.currentTimeMillis()
        val rideTimeSeconds = deriveRideTimeSeconds(now)

        return EUCData(
            speed = speed,
            voltage = voltage,
            current = current,
            temperature = temperature,
            batteryLevel = battery,
            distance = tripDistanceKm,
            power = voltage * current,
            pwm = pwm,
            timestamp = now,
            rawData = frame,
            manufacturer = manufacturer,
            model = model,
            serialNumber = null,
            firmwareVersion = if (versionRaw > 0) formatVersion(versionRaw) else null,
            isCharging = chargeMode > 0,
            chargingStatus = chargeMode,
            rideTime = rideTimeSeconds,
            cellVoltages = getCombinedCellVoltages(),
            mosfetTemperature = lastKnownMosfetTemperature,
            totalDistance = totalDistanceKm,
            angle = angle,
            pedalsMode = pedalsMode,
            autoPowerOffMinutes = autoOffSeconds.takeIf { it > 0 }?.let { it / 60 },
            // Raw words at offsets 24 and 26 are in 0.1 km/h units (200 = 20 km/h), confirmed by
            // WheelLog, the eucplanet captures and the loeuc firmware readout. Above 120.0 km/h -
            // the firmware's own configuration ceiling - the word is a "disabled" marker or noise.
            tiltBackSpeed = speedTiltBackRaw.takeIf { it in 1..1200 }?.let { it / 10 },
            // The tiltback is the max speed SET_SPEED_LIMIT writes: same value, normalized field.
            wheelMaxSpeed = speedTiltBackRaw.takeIf { it in 1..1200 }?.let { it / 10 },
            alarm1Speed = speedAlertRaw.takeIf { it in 1..1200 }?.let { it / 10 },
            // Stock firmware fills offsets 40..45 with the 0x80 "not reported" sentinel; patched
            // builds put the motor probe there instead, in centidegrees capped by the firmware's
            // own 27-entry lookup (about -40..220 C). Anything outside that range stays null.
            motorTemperature = ByteUtils.tryGetSignedShortBE(frame, 40)
                ?.let { it / 100.0 }?.takeIf { it in -40.0..220.0 },
        )
    }

    private fun parseSmartBms(frame: ByteArray) {
        val packetNum = ByteUtils.tryGetUnsignedByte(frame, 46) ?: return
        if (packetNum !in 0..7) return
        // The 0x5F "BMS ADC" frames follow the same page layout as the standard long frames,
        // but the 59..60 MOSFET mapping below is the one loeuc read out of the dispatch for the
        // standard frames, so it is not latched from an ADC frame.
        val isAdcFrame = frame.size > 3 && frame[3] == 0x5F.toByte()
        // Page 0/4 carries the real MOSFET temperature in centidegrees at offset 59, the reading
        // the wheel's own screen shows (the realtime body only carries the controller board
        // temperature at offset 18). Read it before the per-page length gate: Patton's 69-byte
        // page-0 payload stops before the battery currents but still carries the MOS word.
        // Only sane samples are latched and stamped onto every telemetry frame, like the Oryx
        // battery percentage.
        if (!isAdcFrame && (packetNum == 0 || packetNum == 4)) {
            ByteUtils.tryGetSignedShortBE(frame, 59)
                ?.let { it / 100.0 }
                ?.takeIf { it in -40.0..200.0 }
                ?.let { lastKnownMosfetTemperature = it }
        }
        val payloadEnd = ByteUtils.getUnsignedByte(frame, 3)
        val requiredEnd = if (packetNum == 0 || packetNum == 4) 73 else 83
        if (payloadEnd < requiredEnd) return
        val bmsIndex = if (packetNum < 4) 1 else 2
        val cellCount = bmsCellCount(lastMajorVersion)
        val cells = bmsCellPages.getOrPut(bmsIndex) { DoubleArray(LEAPERKIM_MAX_BMS_CELLS) }
        when (packetNum) {
            0, 4 -> {
                val bms1CurrentRaw = ByteUtils.tryGetSignedShortBE(frame, 69)
                val bms2CurrentRaw = ByteUtils.tryGetSignedShortBE(frame, 71)
                bms1CurrentRaw?.let { bmsCurrents[1] = it / 100.0 }
                bms2CurrentRaw?.let { bmsCurrents[2] = it / 100.0 }
            }

            1, 5 -> {
                for (i in 0 until 15) {
                    val raw = ByteUtils.tryGetUnsignedShortBE(frame, 53 + i * 2) ?: continue
                    if (i < cellCount) cells[i] = raw / 1000.0
                }
            }

            2, 6 -> {
                for (i in 0 until 15) {
                    val raw = ByteUtils.tryGetUnsignedShortBE(frame, 53 + i * 2) ?: continue
                    val index = i + 15
                    if (index < cellCount) {
                        cells[index] = raw / 1000.0
                    }
                }
            }

            3, 7 -> {
                for (i in 0 until 12) {
                    val raw = ByteUtils.tryGetUnsignedShortBE(frame, 59 + i * 2) ?: continue
                    val index = i + 30
                    if (index < cellCount) {
                        cells[index] = raw / 1000.0
                    }
                }
                val temps = buildList {
                    for (i in 0 until 6) {
                        val raw = ByteUtils.tryGetSignedShortBE(frame, 47 + i * 2) ?: continue
                        add(raw / 100.0)
                    }
                }
                if (temps.isNotEmpty()) {
                    bmsTemperatures[bmsIndex] = temps
                }
            }
        }
    }

    private fun getCombinedCellVoltages(): List<Double>? {
        if (bmsCellPages.isEmpty()) return null
        val combined = bmsCellPages.values
            .flatMap { it.take(bmsCellCount(lastMajorVersion)) }
            .filter { it > 0.0 }
        return combined.ifEmpty { null }
    }

    override fun getBMSData(): List<BMSData> {
        val allIndices =
            (bmsCellPages.keys + bmsTemperatures.keys + bmsCurrents.keys).distinct().sorted()
        return allIndices.map { index ->
            BMSData(
                bmsIndex = index,
                voltage = null,
                current = bmsCurrents[index],
                remainingCapacity = null,
                factoryCapacity = null,
                cycles = null,
                temperatures = bmsTemperatures[index],
                cellVoltages = bmsCellPages[index]?.take(bmsCellCount(lastMajorVersion))
                    ?.filter { it > 0.0 }?.ifEmpty { null },
                isCharging = resolveBmsChargingState(
                    bmsCurrents[index],
                    lastKnownChargeMode?.let { it > 0 }
                )
            )
        }
    }

    protected open fun bmsCellCount(majorVersion: Int?): Int = LEAPERKIM_MAX_BMS_CELLS

    protected open fun decodeSpeed(speedRaw: Short): Double = abs(speedRaw / 10.0)

    private fun isCrcValid(frame: ByteArray, len: Int): Boolean {
        if (frame.size < len + 4) return false
        val calc = EucCrc32.calculate(frame, 0, len)
        val provided = ByteUtils.getUnsignedIntBE(frame, len).toLong()
        return calc == provided
    }

    private fun decodeDistanceKm(frame: ByteArray, offset: Int): Double {
        // Metres: big-endian 16-bit words, with the low word transmitted first.
        val low = ByteUtils.getUnsignedShortBE(frame, offset).toLong()
        val high = ByteUtils.getUnsignedShortBE(frame, offset + 2).toLong()
        return ((high shl 16) or low) / 1000.0
    }

    protected open fun modelByMajorVersion(version: Int): String {
        return when (version) {
            0, 1 -> "Sherman"
            2 -> "Abrams"
            3 -> "Sherman S"
            4 -> "Patton"
            5 -> "Lynx"
            6 -> "Sherman L"
            7 -> "Patton S"
            8 -> "Oryx"
            9 -> "Lynx S"
            else -> "Leaperkim"
        }
    }

    protected open fun estimateBatteryPercent(voltageRaw: Int, majorVersion: Int): Int {
        val battery = when (majorVersion) {
            4, 7 -> ((voltageRaw - 9600) / (12525.0 - 9600.0) * 100.0)
            5, 6, 9 -> ((voltageRaw - 11520) / (15030.0 - 11520.0) * 100.0)
            8 -> ((voltageRaw - 13886) / (17535.0 - 13886.0) * 100.0)
            else -> ((voltageRaw - 7935) / (10020.0 - 7935.0) * 100.0)
        }
        return battery.roundToInt().coerceIn(0, 100)
    }

    protected open fun extractMajorVersion(versionRaw: Int): Int = versionRaw / 1000

    protected open fun formatVersion(versionRaw: Int): String {
        val major = versionRaw / 1000
        val minor = (versionRaw % 1000) / 100
        val patch = versionRaw % 100
        return buildString(9) {
            append(major.toString().padStart(3, '0'))
            append('.')
            append(minor)
            append('.')
            append(patch.toString().padStart(2, '0'))
        }
    }

    private fun deriveRideTimeSeconds(nowMs: Long): Long {
        val start = sessionStartTimestampMs ?: nowMs.also { sessionStartTimestampMs = it }
        return ((nowMs - start) / 1000L).coerceAtLeast(0L)
    }

    override fun createCommand(commandType: CommandType, value: CommandValue): ByteArray {
        return when (commandType) {
            CommandType.LIGHT_ON -> "SetLightON".encodeToByteArray()
            CommandType.LIGHT_OFF -> "SetLightOFF".encodeToByteArray()

            CommandType.SET_HIGH_BEAM -> {
                // High beam is a separate light circuit from the ASCII low-beam toggle.
                // Two vendor frames must be written back-to-back: the LkAp frame followed
                // immediately by the LdAp companion. We concatenate them here; the BLE
                // layer splits at the 20-byte ATT boundary before writing.
                val on = (value as? CommandValue.Toggle)?.value ?: return byteArrayOf()
                buildVendorFrame(LKAP, 13, byteArrayOf(0x01, 0x80.toByte(), 0x80.toByte()), (if (on) 0x01 else 0x00).toByte()) +
                        buildVendorFrame(LDAP, 13, byteArrayOf(0x01, 0x00, 0x80.toByte()), (if (on) 0x01 else 0x00).toByte())
            }

            CommandType.BEEP -> {
                if ((lastMajorVersion ?: 0) < 3) {
                    "b".encodeToByteArray()
                } else {
                    // Modern beep is a two-frame sequence: LkAp + LdAp companion.
                    // Both frames are returned concatenated; the BLE layer splits at
                    // the 20-byte ATT boundary.
                    buildVendorFrame(LKAP, 14, byteArrayOf(0x00, 0x80.toByte(), 0x80.toByte(), 0x80.toByte()), 0x01) +
                            buildVendorFrame(LDAP, 14, byteArrayOf(0x00, 0x00, 0x80.toByte(), 0x80.toByte()), 0x01)
                }
            }

            CommandType.LOCK -> buildLockFrame(locked = true)
            CommandType.UNLOCK -> buildLockFrame(locked = false)

            CommandType.SET_PEDALS_MODE -> {
                when ((value as? CommandValue.Integer)?.value?.coerceIn(0, 2)) {
                    0 -> "SETh".encodeToByteArray()
                    1 -> "SETm".encodeToByteArray()
                    2 -> "SETs".encodeToByteArray()
                    else -> byteArrayOf()
                }
            }

            CommandType.SET_PEDAL_ANGLE -> {
                // Signed tenths-of-a-degree, encoded as a signed i8.
                // Example: -36 → 0xDC (confirmed from Lynx S capture, slider -3.6°).
                val tenths = (value as? CommandValue.Integer)?.value ?: return byteArrayOf()
                val clamped = tenths.coerceIn(-128, 127)
                buildVendorFrame(
                    LKAP, 16,
                    byteArrayOf(0x01, 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte()),
                    clamped.toByte()
                )
            }

            CommandType.SET_RIDE_MODE -> {
                // Ride-mode scalar 0..100.
                val scalar = (value as? CommandValue.Integer)?.value?.coerceIn(0, 100) ?: return byteArrayOf()
                buildVendorFrame(
                    LDAP, 15,
                    byteArrayOf(0x01, 0x02, 0x80.toByte(), 0x80.toByte(), 0x80.toByte()),
                    scalar.toByte()
                )
            }

            CommandType.SET_PWM_LIMIT -> {
                // PWM percentage 0..100.
                val percent = (value as? CommandValue.Integer)?.value?.coerceIn(0, 100) ?: return byteArrayOf()
                buildVendorFrame(
                    LDAP, 18,
                    byteArrayOf(
                        0x01, 0x02,
                        0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte()
                    ),
                    percent.toByte()
                )
            }

            CommandType.SET_SPEED_LIMIT -> {
                // Tiltback speed in km/h, LdAp form (Lynx S capture: slider 21 km/h <-> 0x15).
                val kmh = (value as? CommandValue.Integer)?.value?.coerceIn(1, 99) ?: return byteArrayOf()
                buildVendorFrame(
                    LDAP, 17,
                    byteArrayOf(0x01, 0x02, 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte()),
                    kmh.toByte()
                )
            }

            CommandType.SET_ALARM_SPEED -> {
                // Alarm speed in km/h, LkAp companion form (Lynx S capture: 20 km/h <-> 0x14).
                val kmh = (value as? CommandValue.Integer)?.value?.coerceIn(1, 99) ?: return byteArrayOf()
                buildVendorFrame(
                    LKAP, 17,
                    byteArrayOf(0x01, 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte(), 0x80.toByte()),
                    kmh.toByte()
                )
            }

            CommandType.REQUEST_DIAGNOSTIC_LOG -> return diagnosticLog.start()
            CommandType.CANCEL_DIAGNOSTIC_LOG -> return diagnosticLog.cancel()

            CommandType.RESET_TRIP -> "CLEARMETER".encodeToByteArray()
            CommandType.CUSTOM -> {
                when (value) {
                    is CommandValue.Bytes -> value.copyBytes()
                    is CommandValue.Text -> value.value.encodeToByteArray()
                    else -> byteArrayOf()
                }
            }

            else -> byteArrayOf()
        }
    }

    /**
     * Build a lock/unlock command frame (25-byte LdAp vendor frame).
     *
     * The payload encodes the current wall-clock timestamp (day/hour/minute/second)
     * followed by the lock state byte. The timestamp must reflect the actual moment
     * of the write — the wheel validates freshness and rejects frozen timestamps.
     *
     * Wire format verified from a Lynx S btsnoop: twenty paired lock/unlock writes
     * all match within one second of the HCI packet timestamp.
     */
    private fun buildLockFrame(locked: Boolean): ByteArray = buildLockFrame(locked, clock.localDateTime())

    fun buildLockFrame(locked: Boolean, now: EucDateTime): ByteArray {
        val state: Byte = if (locked) 0x01 else 0x00
        val day = now.dayOfMonth.toByte()
        val hour = now.hour.toByte()
        val minute = now.minute.toByte()
        val second = now.second.toByte()
        return buildVendorFrame(
            LDAP, 25,
            byteArrayOf(
                0x00, 0x05, 0x1A, 0x06,
                day, hour, minute, second,
                0x02, 0x04, 0x0C, 0xAB.toByte(),
                state, 0x00, 0x00,
            ),
            0x00
        )
    }

    /**
     * Build a LeaperKim vendor frame.
     *
     * Layout: [magic 4] [totalLen 1] [payloadHead N] [valueByte 1] [CRC32-BE 4]
     * where totalLen = 4 + 1 + payloadHead.size + 1 + 4.
     * CRC32 covers everything from magic[0] through the last non-CRC byte.
     */
    private fun buildVendorFrame(
        magic: ByteArray,
        totalLen: Int,
        payloadHead: ByteArray,
        valueByte: Byte
    ): ByteArray {
        val out = ByteArray(totalLen)
        magic.copyInto(out, 0)
        out[4] = totalLen.toByte()
        payloadHead.copyInto(out, 5)
        out[5 + payloadHead.size] = valueByte
        val crcEnd = totalLen - 4
        val crc = EucCrc32.calculate(out, 0, crcEnd).toInt()
        out[crcEnd]     = ((crc ushr 24) and 0xFF).toByte()
        out[crcEnd + 1] = ((crc ushr 16) and 0xFF).toByte()
        out[crcEnd + 2] = ((crc ushr 8)  and 0xFF).toByte()
        out[crcEnd + 3] = (crc           and 0xFF).toByte()
        return out
    }

    override fun isDeviceReady(data: EUCData): Boolean {
        return data.voltage > 40.0 && data.model.isNotBlank()
    }

    override fun resetSession() {
        frameParser.reset()
        outbox.clear()
        sessionStartTimestampMs = null
        lastMajorVersion = null
        lastOryxBatterySoc = -1
        lastKnownChargeMode = null
        lastKnownTiltBackSpeed = null
        lastKnownAlarmSpeed = null
        lastKnownMosfetTemperature = null
        diagnosticLog.reset()
        bmsCellPages.clear()
        bmsTemperatures.clear()
        bmsCurrents.clear()
    }
}