KingsongSyncProtocol.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.EucClock
import io.github.tritbool.euc.ble.core.EucRandom
import io.github.tritbool.euc.ble.frames.ByteByByteFrameParser
import io.github.tritbool.euc.ble.models.BMSData
import io.github.tritbool.euc.ble.models.EUCData
import io.github.tritbool.euc.ble.models.AuthenticationState
import io.github.tritbool.euc.ble.models.WheelLockState
import io.github.tritbool.euc.ble.models.WheelSecurityState
import io.github.tritbool.euc.ble.models.WheelSecurityEvent
import io.github.tritbool.euc.ble.models.PasswordOperation
import io.github.tritbool.euc.ble.models.PasswordOperationStatus
import io.github.tritbool.euc.ble.models.resolveBmsChargingState
import io.github.tritbool.euc.ble.core.EucUuid as UUID

/**
 * Improved KingSong protocol: tolerant parsing, header resync, header-aware frame reassembly
 * using ByteByByteFrameParser, safe bounds checks, optional cell voltages parsing, and clamped command generation.
 *
 * Supports frame types: 0xA9 (live telemetry + pedal hardness), 0xB9 (distance/fan/motorTemperature),
 * 0xBB (name/model/version),
 * 0xB3 (serial number), 0xF5 (CPU load/PWM), 0xF6 (dynamic speed limit), 0xA4/0xB5 (speed settings),
 * 0xF1/0xF2 (Smart BMS data).
 */
class KingsongSyncProtocol(
    private val clock: EucClock,
    private val unlockRandom: EucRandom
) : SyncEucProtocol {

    override fun hasSpeedMeasurement(data: EUCData): Boolean = true

    private val header = BLEConstants.KINGSONG_FRAME_HEADER_1
    private val FRAME_LENGTH = 20

    private val unpackBuffer = ArrayList<Byte>()

    /**
     * Stateful byte-stream reassembler for fixed-length KingSong frames.
     *
     * Input chunks may be truncated, concatenated, or prefixed with junk.
     * Each emitted item is exactly one 20-byte frame beginning with AA 55.
     *
     * `AA 55` is the only accepted inbound header. A final lone `AA` is kept
     * when resynchronising because the next chunk may begin with `55`.
     */
    private val unpacker: (Byte) -> List<ByteArray> = { byte ->
        unpackBuffer.add(byte)

        val frames = mutableListOf<ByteArray>()

        fun findHeaderIndex(): Int {
            var index = 0
            while (index + 1 < unpackBuffer.size) {
                if (
                    unpackBuffer[index] == header[0] &&
                    unpackBuffer[index + 1] == header[1]
                ) {
                    return index
                }
                index++
            }
            return -1
        }

        while (true) {
            val headerIndex = findHeaderIndex()

            if (headerIndex < 0) {
                /*
                 * Preserve only a possible first byte of a split AA 55 header.
                 * Any other bytes cannot begin a valid incoming KingSong frame.
                 */
                val keepLastAa =
                    unpackBuffer.lastOrNull() == header[0]

                unpackBuffer.clear()

                if (keepLastAa) {
                    unpackBuffer.add(header[0])
                }

                break
            }

            /*
             * Discard bytes before the next valid AA 55 header.
             * Do this before checking size so a fragmented valid frame remains
             * aligned at index 0 until its missing bytes arrive.
             */
            if (headerIndex > 0) {
                unpackBuffer.subList(0, headerIndex).clear()
            }

            /*
             * A KingSong short frame is complete only at exactly 20 buffered
             * bytes from its AA 55 header. Do not use the next header as an end
             * delimiter, and do not emit bytes beyond this frame.
             */
            if (unpackBuffer.size < FRAME_LENGTH) {
                break
            }

            frames += ByteArray(FRAME_LENGTH) { index ->
                unpackBuffer[index]
            }

            unpackBuffer.subList(0, FRAME_LENGTH).clear()
        }

        frames
    }

    override val manufacturer: String = "KingSong"
    override val protocolId: String = "KingsongProtocol"
    override val preferredWriteType: ProtocolWriteType = ProtocolWriteType.NO_RESPONSE
    override val supportedCommandTypes: Set<CommandType>
        get() = CommandCatalogue.supportedTypes(getCommandDescriptors())

    override fun commandStateError(commandId: String): String? = when {
        commandId == CommandType.SET_SPEED_LIMIT.name &&
            (lastKnownAlarm1Speed == null || lastKnownAlarm2Speed == null || lastKnownAlarm3Speed == null) ->
            "Wheel alarm settings must be received before changing the speed limit"
        commandId == CommandType.SET_ALARM_SPEED.name && lastKnownWheelMaxSpeed == null ->
            "Wheel maximum speed must be received before changing alarms"
        else -> null
    }

    override fun getServiceUUID(): UUID = UUID.fromString(BLEConstants.KINGSONG_SERVICE_UUID)
    override fun getDataCharacteristicUUID(): UUID =
        UUID.fromString(BLEConstants.KINGSONG_READ_CHARACTERISTIC)

    private fun ensureRange(data: ByteArray, offset: Int, length: Int): Boolean {
        return offset >= 0 && data.size >= offset + length
    }


    private fun readWordSwappedLE32(frame: ByteArray, offset: Int): Int {
        val b0 = frame[offset].toInt() and 0xFF
        val b1 = frame[offset + 1].toInt() and 0xFF
        val b2 = frame[offset + 2].toInt() and 0xFF
        val b3 = frame[offset + 3].toInt() and 0xFF

        return (b1 shl 24) or (b0 shl 16) or (b3 shl 8) or b2
    }

    private fun isPlausibleDistanceKm(distanceKm: Double): Boolean =
        distanceKm in 0.0..MAX_PLAUSIBLE_DISTANCE_KM

    /**
     * The A9 odometer is word-swapped on captured KingSong firmwares, but some
     * models/firmwares send it as plain little-endian, which inflates the
     * word-swapped reading by up to ~65536x (a 1000 km odometer reads as
     * ~1.1e6 km). Prefer the word-swapped reading when plausible, fall back to
     * the plain LE reading when it is the only plausible one, and otherwise
     * keep the last known value instead of publishing garbage distance.
     * See https://github.com/Tritbool/euc_ble_library/issues/103.
     */
    private fun resolveA9TotalDistance(data: ByteArray, offset: Int): Double {
        val swappedKm = (readWordSwappedLE32(data, offset).toLong() and 0xFFFFFFFFL) / 1000.0
        if (isPlausibleDistanceKm(swappedKm)) return swappedKm

        val plainKm = ByteUtils.getUnsignedIntLE(data, offset) / 1000.0
        if (isPlausibleDistanceKm(plainKm)) return plainKm

        return lastKnownTotalDistance ?: 0.0
    }


    // Internal buffer used by the unpacker

    private val byteParser = ByteByByteFrameParser(unpacker, resetUnpacker = {
        unpackBuffer.clear()
    })
    private var unlockChallenge: IntArray? = null
    private class PendingPasswordOperation(
        val operation: PasswordOperation,
        val expected: ByteArray
    )
    private var pendingPasswordOperation: PendingPasswordOperation? = null
    private var securityState = WheelSecurityState()
    private val outbox = ProtocolOutbox()
    override fun getSecurityState(): WheelSecurityState = securityState

    override fun resetSession() {
        run {
            byteParser.reset()
            securityState = WheelSecurityState()
            clearPasswordOperation()
            outbox.clear()
            unlockChallenge = null
            lastKnownDynamicSpeedLimit = null
            lastKnownWheelMaxSpeed = null
            lastKnownAlarm1Speed = null
            lastKnownAlarm2Speed = null
            lastKnownAlarm3Speed = null
            sessionStartTimestampMs = null
            lastKnownPwm = null
            lastKnownModel = null
            lastKnownFirmwareVersion = null
            lastKnownSerialNumber = null
            lastKnownTopSpeed = null
            lastKnownFanStatus = null
            lastKnownChargingStatus = null
            lastKnownIsCharging = null
            lastKnownMotorTemperature = null
            lastKnownCpuLoad = null
            lastKnownWheelDistance = null
            lastKnownTotalDistance = null
            lastKnownLightMode = null
            lastKnownPedalsMode = null
            inferredSeriesCells = null
            bmsCellPages.clear()
            bmsSummary.clear()
            bmsTemperatures.clear()
        }
    }

    override fun canSendCommand(payload: ByteArray): Boolean = run {
        val isLockCommand = payload.size >= 17 &&
            payload[0] == header[0] && payload[1] == header[1] && payload[16] == 0x5D.toByte()
        (!isLockCommand || securityState.authentication != AuthenticationState.REQUIRED) &&
            (!isPasswordCommand(payload) || pendingPasswordOperation == null)
    }

    private fun isPasswordCommand(payload: ByteArray): Boolean =
        payload.size >= 17 && payload[0] == header[0] && payload[1] == header[1] &&
            payload[16].toInt() in 0x41..0x42

    override fun canRetryCommand(payload: ByteArray): Boolean = !isPasswordCommand(payload)

    override fun onCommandSubmitted(payload: ByteArray) {
        run {
            if (!isPasswordCommand(payload) || !hasStandardTrailer(payload) ||
                pendingPasswordOperation != null ||
                (2..5).any { payload[it].toInt() !in 0x30..0x39 }
            ) return
            val operation = if (payload[16] == 0x42.toByte()) {
                if ((6..15).any { payload[it] != 0.toByte() }) return
                PasswordOperation.REMOVE
            } else {
                if ((10..15).any { payload[it] != 0.toByte() }) return
                when {
                    (6..9).all { payload[it] == 0.toByte() } -> PasswordOperation.SET
                    (6..9).all { payload[it].toInt() in 0x30..0x39 } -> PasswordOperation.CHANGE
                    else -> return
                }
            }
            // Retain only the expected reply, never the old/current password.
            val expected = if (operation == PasswordOperation.REMOVE) {
                ByteArray(4) { 0xFF.toByte() }
            } else {
                payload.copyOfRange(2, 6)
            }
            pendingPasswordOperation = PendingPasswordOperation(operation, expected)
            outbox.push(ProtocolOutput.StartTimer(PASSWORD_TIMER, PASSWORD_OPERATION_TIMEOUT_MS))
        }
    }

    override fun onTimer(id: String) {
        if (id == PASSWORD_TIMER && pendingPasswordOperation != null) {
            finishPasswordOperation(PasswordOperationStatus.TIMEOUT_UNCONFIRMED)
        }
    }

    private fun hasStandardTrailer(frame: ByteArray, offset: Int = 0): Boolean =
        offset >= 0 && frame.size - offset == FRAME_LENGTH && frame[offset + 17] == 0x14.toByte() &&
            frame[offset + 18] == 0x5A.toByte() && frame[offset + 19] == 0x5A.toByte()

    private fun clearPasswordOperation() {
        pendingPasswordOperation?.let {
            outbox.push(ProtocolOutput.CancelTimer(PASSWORD_TIMER))
            it.expected.fill(0)
        }
        pendingPasswordOperation = null
    }

    private fun finishPasswordOperation(status: PasswordOperationStatus) {
        val operation = pendingPasswordOperation?.operation ?: return
        clearPasswordOperation()
        outbox.push(ProtocolOutput.SecurityEvent(WheelSecurityEvent.PasswordOperationResult(operation, status)))
    }

    //private val scope = CoroutineScope(Dispatchers.IO)
    private var sessionStartTimestampMs: Long? = null
    private var lastKnownPwm: Double? = null

    // Stateful fields accumulated from non-A9 frames
    private var lastKnownModel: String? = null
    private var lastKnownFirmwareVersion: String? = null
    private var lastKnownSerialNumber: String? = null
    private var lastKnownTopSpeed: Double? = null
    private var lastKnownFanStatus: Int? = null
    private var lastKnownChargingStatus: Int? = null
    private var lastKnownIsCharging: Boolean? = null
    private var lastKnownMotorTemperature: Double? = null
    private var lastKnownCpuLoad: Int? = null
    private var lastKnownDynamicSpeedLimit: Double? = null
    private var lastKnownAlarm1Speed: Int? = null
    private var lastKnownAlarm2Speed: Int? = null
    private var lastKnownAlarm3Speed: Int? = null
    private var lastKnownWheelMaxSpeed: Int? = null
    private var lastKnownWheelDistance: Double? = null
    private var lastKnownTotalDistance: Double? = null
    private var lastKnownLightMode: Int? = null
    private var lastKnownPedalsMode: Int? = null
    private var inferredSeriesCells: Int? = null

    // BMS cell data: bmsIndex (1 or 2) -> array of cell voltages
    private val bmsCellPages: MutableMap<Int, DoubleArray> = mutableMapOf()

    // BMS summary data from page 0x00: bmsIndex -> [voltage, current, remainingCapacity, factoryCapacity, cycles]
    private val bmsSummary: MutableMap<Int, BMSSummary> = mutableMapOf()

    // BMS temperature data from page 0x01: bmsIndex -> list of temperature values in °C
    private val bmsTemperatures: MutableMap<Int, List<Double>> = mutableMapOf()

    private data class BMSSummary(
        val voltage: Double,       // volts
        val current: Double,       // amps
        val remainingCapacity: Int, // mAh
        val factoryCapacity: Int,  // mAh
        val cycles: Int            // charge cycles
    )

    companion object {
        private const val MAX_BMS_CELLS = 30

        // Frame types
        private const val FRAME_TYPE_A9 = 0xA9
        private const val FRAME_TYPE_B9 = 0xB9
        private const val FRAME_TYPE_BB = 0xBB
        private const val FRAME_TYPE_B3 = 0xB3
        private const val FRAME_TYPE_F5 = 0xF5
        private const val FRAME_TYPE_F6 = 0xF6
        private const val FRAME_TYPE_A4 = 0xA4
        private const val FRAME_TYPE_B5 = 0xB5
        private const val FRAME_TYPE_F1 = 0xF1
        private const val FRAME_TYPE_F2 = 0xF2

        // BMS page types
        private const val BMS_PAGE_SUMMARY = 0x00
        private const val BMS_PAGE_TEMPERATURES = 0x01
        private const val BMS_PAGE_CELL_VOLTAGES_START = 0x02

        // Special byte values
        private const val BMS_FRAME_OFFSET = 0xF0
        /** Frame 0xA9 byte 15: marks the pedal-mode byte at offset 14 as meaningful. */
        private const val PEDALS_MODE_VALID = 0xE0
        /** Highest pedal-mode index KingSong is known to report; newer indices stay unreported. */
        private const val PEDALS_MODE_MAX = 3

        // Serial number length
        private const val SERIAL_NUMBER_LENGTH = 17

        // Frame byte offsets
        private const val OFFSET_VOLTAGE = 2
        private const val OFFSET_SPEED = 4
        private const val OFFSET_MESSAGE_TYPE = 16
        private const val OFFSET_PAGE_NUM = 17
        private const val OFFSET_PEDALS_MODE = 14
        private const val OFFSET_PEDALS_MODE_MARKER = 15

        private const val QUERY_ID_REQUEST_ALARMS = "ks.request-alarms"
        const val PASSWORD_OPERATION_TIMEOUT_MS = 3000L
        private const val PASSWORD_TIMER = "kingsong.password"

        // KingSong never transmits a battery percentage; it is derived from the
        // per-cell pack voltage on a linear 3.10 V (0 %) .. 4.15 V (100 %) line,
        // matching the official KingSong app (eucplanet KingsongParser captures).
        private const val KS_EMPTY_V_PER_CELL = 3.10
        private const val KS_FULL_V_PER_CELL = 4.15
        private const val MAX_PLAUSIBLE_DISTANCE_KM = 1_000_000.0

        // Upper bound per cell used to infer the pack class from voltage alone.
        private const val MAX_V_PER_CELL_FOR_INFERENCE = 4.25

        // KingSong pack classes: 67 V, 84 V, 100 V, 126 V, 151 V, 176 V.
        private val KNOWN_SERIES_COUNTS = intArrayOf(16, 20, 24, 30, 36, 42)

        /**
         * Number of cells in series for a KingSong model name reported in frame 0xBB
         * (e.g. "KS-S18", "KS-16X"), or null when the model is unknown.
         */
        fun seriesCellsForModel(model: String?): Int? {
            val n = model?.lowercase() ?: return null
            return when {
                "s22" in n || "s20" in n || "f16" in n  -> 30
                "s19" in n -> 24
                "s18" in n || "s16" in n -> 20
                "f22" in n -> 42
                "f18" in n -> 36
                "ks-18" in n || "ks18" in n -> 20
                "ks-16x" in n || "ks16x" in n -> 20
                "ks-16" in n || "ks16" in n || "ks-16s" in n || "ks16s" in n || "ks-14" in n || "ks14" in n -> 16
                else -> null
            }
        }

        /** Smallest known pack class able to reach [voltage]. */
        fun seriesCellsForVoltage(voltage: Double): Int? {
            if (voltage <= 0.0) return null
            return KNOWN_SERIES_COUNTS.firstOrNull { voltage <= it * MAX_V_PER_CELL_FOR_INFERENCE }
                ?: KNOWN_SERIES_COUNTS.last()
        }

        fun batteryPercentFromVoltage(voltage: Double, seriesCells: Int): Int {
            if (voltage <= 0.0 || seriesCells <= 0) return 0
            val perCell = voltage / seriesCells
            val raw = (perCell - KS_EMPTY_V_PER_CELL) * 100.0 /
                    (KS_FULL_V_PER_CELL - KS_EMPTY_V_PER_CELL)
            return raw.toInt().coerceIn(0, 100)
        }
    }

    private fun parseFrame(data: ByteArray): EUCData? {
        if (data.isEmpty()) return null

        val headerIdx = run {
            for (i in 0..(data.size - 2)) {
                if (data[i] == header[0] && data[i + 1] == header[1]) return@run i

            }
            -1
        }
        if (headerIdx < 0) return null

        if (data.size - headerIdx < FRAME_LENGTH) {
            return null
        }

        val messageType = ByteUtils.getUnsignedByte(data, headerIdx + OFFSET_MESSAGE_TYPE)
        return when (messageType) {
            0x43 -> {
                val pending = pendingPasswordOperation
                if (pending != null && hasStandardTrailer(data, headerIdx) &&
                    data[headerIdx + 6] == 0x01.toByte() &&
                    pending.expected.indices.all { data[headerIdx + 2 + it] == pending.expected[it] }
                ) {
                    finishPasswordOperation(PasswordOperationStatus.CONFIRMED)
                }
                null
            }
            0x46, 0x5F -> {
                // Only known status values with the standard trailer can confirm security state.
                if (data[headerIdx + 17] == 0x14.toByte() &&
                    data[headerIdx + 18] == 0x5A.toByte() &&
                    data[headerIdx + 19] == 0x5A.toByte()
                ) {
                    val status = ByteUtils.getUnsignedByte(data, headerIdx + 2)
                    val state = securityState
                    if (status == 0 || status == 1) {
                        if (messageType == 0x5F &&
                            (4..9).all { ByteUtils.getUnsignedByte(data, headerIdx + it) in 0x30..0x39 }
                        ) {
                            unlockChallenge = intArrayOf(4, 6, 8).map {
                                ByteUtils.getUnsignedByte(data, headerIdx + it) - 0x30
                            }.toIntArray()
                        }
                        securityState = if (messageType == 0x46) {
                            state.copy(authentication = if (status == 1)
                                AuthenticationState.REQUIRED else AuthenticationState.AUTHENTICATED)
                        } else {
                            state.copy(lock = if (status == 1)
                                WheelLockState.LOCKED else WheelLockState.UNLOCKED)
                        }
                        val confirmed = securityState
                        outbox.push(ProtocolOutput.SecurityStateChanged(confirmed))
                        outbox.push(ProtocolOutput.SecurityEvent(if (messageType == 0x46) {
                            WheelSecurityEvent.AuthenticationStatus(confirmed.authentication)
                        } else {
                            WheelSecurityEvent.LockStatus(confirmed.lock)
                        }))
                    }
                }
                null
            }
            FRAME_TYPE_A9 -> parseTypeA9(data, headerIdx)
            FRAME_TYPE_B9 -> {
                parseTypeB9(data, headerIdx)
                null
            }

            FRAME_TYPE_BB -> {
                parseTypeBB(data, headerIdx)
                null
            }

            FRAME_TYPE_B3 -> {
                parseTypeB3(data, headerIdx)
                null
            }

            FRAME_TYPE_F5 -> {
                parseTypeF5(data, headerIdx)
                null
            }

            FRAME_TYPE_F6 -> {
                parseTypeF6(data, headerIdx)
                null
            }

            FRAME_TYPE_A4, FRAME_TYPE_B5 -> {
                parseTypeA4B5(data, headerIdx)
                null
            }

            FRAME_TYPE_F1, FRAME_TYPE_F2 -> {
                parseTypeBMS(data, headerIdx, messageType)
                null
            }

            else -> null
        }
    }

    private fun parseTypeA9(data: ByteArray, base: Int): EUCData? {
        try {
            val voltage = if (ensureRange(data, base + OFFSET_VOLTAGE, 2))
                ByteUtils.getUnsignedShortLE(data, base + OFFSET_VOLTAGE) / 100.0 else 0.0

            val speed = if (ensureRange(data, base + OFFSET_SPEED, 2))
                ByteUtils.getUnsignedShortLE(data, base + OFFSET_SPEED) / 100.0 else 0.0

            val totalDistRaw = if (ensureRange(data, base + 6, 4))
                resolveA9TotalDistance(data, base + 6) else 0.0

            val current = if (ensureRange(data, base + 10, 2))
                ByteUtils.getSignedShortLE(data, base + 10) / 100.0 else 0.0

            val temperature = if (ensureRange(data, base + 12, 2))
                ByteUtils.getSignedShortLE(data, base + 12) / 100.0 else 0.0

            // Byte 15 is a validity marker, not a battery level: KingSong never transmits a
            // battery percentage, so it is always derived from the pack voltage. When it reads
            // 0xE0, byte 14 is the pedal hardness the wheel is running -- the only place
            // KingSong ever reports it back, since there is no settings-read frame for it.
            // Frames whose marker is not 0xE0 say nothing, so the last known mode stands.
            if (ensureRange(data, base + OFFSET_PEDALS_MODE_MARKER, 1) &&
                ByteUtils.getUnsignedByte(data, base + OFFSET_PEDALS_MODE_MARKER) == PEDALS_MODE_VALID &&
                ensureRange(data, base + OFFSET_PEDALS_MODE, 1)
            ) {
                val pedalsMode = ByteUtils.getUnsignedByte(data, base + OFFSET_PEDALS_MODE)
                if (pedalsMode in 0..PEDALS_MODE_MAX) lastKnownPedalsMode = pedalsMode
            }

            val batteryLevel = estimateBatteryPercent(voltage)

            // === Sanity filters ===
            if (voltage !in 40.0..180.0) return null
            if (speed !in 0.0..80.0) return null
            if (temperature !in -40.0..100.0) return null
            if (current !in -200.0..200.0) return null

            // Charging state is reported by frame 0xB9 (byte 13).
            val isCharging = (lastKnownChargingStatus ?: 0) != 0
            lastKnownIsCharging = isCharging

            lastKnownTotalDistance = totalDistRaw

            val power = voltage * current
            val now = clock.currentTimeMillis()
            val rideTimeSeconds = deriveRideTimeSeconds(now)

            return EUCData(
                speed = speed,
                voltage = voltage,
                current = current,
                temperature = temperature,
                batteryLevel = batteryLevel,
                distance = lastKnownWheelDistance ?: 0.0,
                power = power,
                pwm = lastKnownPwm,
                timestamp = now,
                rawData = data,
                manufacturer = manufacturer,
                model = lastKnownModel ?: "KingSong",
                serialNumber = lastKnownSerialNumber,
                firmwareVersion = lastKnownFirmwareVersion,
                isCharging = isCharging,
                rideTime = rideTimeSeconds,
                cellVoltages = getCombinedCellVoltages(),
                motorTemperature = lastKnownMotorTemperature,
                totalDistance = lastKnownTotalDistance?: totalDistRaw,
                topSpeed = lastKnownTopSpeed,
                fanStatus = lastKnownFanStatus,
                chargingStatus = lastKnownChargingStatus,
                cpuLoad = lastKnownCpuLoad,
                speedLimit = lastKnownWheelMaxSpeed?.toDouble(),
                dynamicSpeedLimit = lastKnownDynamicSpeedLimit,
                alarm1Speed = lastKnownAlarm1Speed,
                alarm2Speed = lastKnownAlarm2Speed,
                alarm3Speed = lastKnownAlarm3Speed,
                wheelMaxSpeed = lastKnownWheelMaxSpeed,
                wheelDistance = lastKnownWheelDistance,
                lightMode = lastKnownLightMode,
                pedalsMode = lastKnownPedalsMode
            )
        } catch (_: Exception) {
            return null
        }
    }

    /**
     * Frame 0xB9: Distance/Time/Fan/ChargingStatus/MotorTemperature
     * Legacy: trip distance in meters (uint32 LE @2), top speed in 0.01 km/h
     * (uint16 LE @8), fanStatus(@12), chargingStatus(@13), and
     * motorTemperature in 0.01 °C (uint16 LE @14).
     */
    private fun parseTypeB9(data: ByteArray, base: Int) {
        if (ensureRange(data, base + 2, 4)) {
            lastKnownWheelDistance = ByteUtils.getUnsignedIntLE(data, base + 2) / 1000.0
        }
        if (ensureRange(data, base + 8, 2)) {
            lastKnownTopSpeed = ByteUtils.getUnsignedShortLE(data, base + 8) / 100.0
        }
        if (ensureRange(data, base + 12, 1)) {
            lastKnownFanStatus = ByteUtils.getUnsignedByte(data, base + 12)
        }
        if (ensureRange(data, base + 13, 1)) {
            lastKnownChargingStatus = ByteUtils.getUnsignedByte(data, base + 13)
            lastKnownIsCharging = lastKnownChargingStatus != 0
        }
        if (ensureRange(data, base + 14, 2)) {
            lastKnownMotorTemperature = ByteUtils.getUnsignedShortLE(data, base + 14) / 100.0
        }
        // Byte 10 of the 0xB9 frame echoes the current light state from the wheel.
        // 0x12 = light ON, 0x13 = light OFF, 0x14 = AUTO mode (eucplanet parseLightOn).
        if (ensureRange(data, base + 10, 1)) {
            lastKnownLightMode = when (ByteUtils.getUnsignedByte(data, base + 10)) {
                0x12 -> 1  // ON
                0x13 -> 0  // OFF
                0x14 -> 2  // AUTO
                else -> lastKnownLightMode
            }
        }
    }

    /**
     * Frame 0xBB: Name/Model/Version
     * Bytes 2..15: null-terminated ASCII name string (e.g. "KS-16X-1234")
     * Model is derived from name parts; version from last segment.
     */
    private fun parseTypeBB(data: ByteArray, base: Int) {
        if (!ensureRange(data, base + 2, 14)) return
        var end = 0
        for (i in 0 until 14) {
            if (data[base + 2 + i] == 0.toByte()) break
            end++
        }
        if (end == 0) return
        val name = data.decodeToString(base + 2, base + 2 + end).trim()
        val parts = name.split("-")
        if (parts.size >= 2) {
            lastKnownModel = parts.dropLast(1).joinToString("-")
            try {
                val versionInt = parts.last().toInt()
                lastKnownFirmwareVersion = "${versionInt / 100}.${(versionInt % 100).toString().padStart(2, '0')}"
            } catch (_: NumberFormatException) {
                // version part not numeric, keep model as full name
                lastKnownModel = name
            }
        } else {
            lastKnownModel = name
        }
    }

    /**
     * Frame 0xB3: Serial Number
     * Bytes 2..15 (14 bytes) + bytes 17..19 (3 bytes) = 17-char serial
     */
    private fun parseTypeB3(data: ByteArray, base: Int) {
        if (!ensureRange(data, base + 2, 14)) return
        if (!ensureRange(data, base + 17, 3)) return
        val snBytes = ByteArray(SERIAL_NUMBER_LENGTH)
        data.copyInto(snBytes, destinationOffset = 0, startIndex = base + 2, endIndex = base + 16)
        data.copyInto(snBytes, destinationOffset = 14, startIndex = base + 17, endIndex = base + 20)
        lastKnownSerialNumber = snBytes.decodeToString().trimEnd('\u0000').trim()
    }

    private fun parseTypeF5(data: ByteArray, base: Int) {
        if (ensureRange(data, base + 14, 1)) {
            lastKnownCpuLoad = ByteUtils.getUnsignedByte(data, base + 14)
        }
        if (!ensureRange(data, base + 15, 1)) return
        val outputByte = ByteUtils.getUnsignedByte(data, base + 15)
        lastKnownPwm = outputByte.toDouble()
    }

    /**
     * Frame 0xF6: Runtime speed ceiling, not the configured max-speed setting.
     * uint16 LE @2, in 0.01 km/h units
     */
    private fun parseTypeF6(data: ByteArray, base: Int) {
        if (!ensureRange(data, base + 2, 2)) return
        lastKnownDynamicSpeedLimit = ByteUtils.getUnsignedShortLE(data, base + 2) / 100.0
    }

    /**
     * Frame 0xA4 / 0xB5: Alarm speeds and max speed
     * alarm1 @4, alarm2 @6, alarm3 @8, maxSpeed @10 (all single bytes)
     */
    private fun parseTypeA4B5(data: ByteArray, base: Int) {
        if (ensureRange(data, base + 4, 1)) {
            lastKnownAlarm1Speed = ByteUtils.getUnsignedByte(data, base + 4)
        }
        if (ensureRange(data, base + 6, 1)) {
            lastKnownAlarm2Speed = ByteUtils.getUnsignedByte(data, base + 6)
        }
        if (ensureRange(data, base + 8, 1)) {
            lastKnownAlarm3Speed = ByteUtils.getUnsignedByte(data, base + 8)
        }
        if (ensureRange(data, base + 10, 1)) {
            lastKnownWheelMaxSpeed = ByteUtils.getUnsignedByte(data, base + 10)
        }
    }

    /**
     * Frame 0xF1/0xF2: Smart BMS data
     * BMS number = messageType - BMS_FRAME_OFFSET (1 or 2)
     * Page number @17 determines what data is in the payload:
     *   BMS_PAGE_SUMMARY: voltage, current, remaining/factory cap, cycles
     *   BMS_PAGE_TEMPERATURES: temperatures (6 probes + MOS temp)
     *   BMS_PAGE_CELL_VOLTAGES_START..0x06: cell voltages (7 cells per page)
     */
    private fun parseTypeBMS(data: ByteArray, base: Int, messageType: Int) {
        val bmsIndex = messageType - BMS_FRAME_OFFSET
        if (!ensureRange(data, base + OFFSET_PAGE_NUM, 1)) return
        val pageNum = ByteUtils.getUnsignedByte(data, base + OFFSET_PAGE_NUM)

        when (pageNum) {
            0x00 -> {
                // Page 0x00: BMS voltage, current, remaining capacity, factory capacity, cycles
                if (!ensureRange(data, base + 2, 10)) return
                val bmsVoltage = ByteUtils.getUnsignedShortLE(data, base + 2) / 100.0
                val bmsCurrent = ByteUtils.getSignedShortLE(data, base + 4) / 100.0
                val remainingCapacity = ByteUtils.getUnsignedShortLE(data, base + 6)
                val factoryCapacity = ByteUtils.getUnsignedShortLE(data, base + 8)
                val cycles = ByteUtils.getUnsignedShortLE(data, base + 10)
                bmsSummary[bmsIndex] = BMSSummary(
                    voltage = bmsVoltage,
                    current = bmsCurrent,
                    remainingCapacity = remainingCapacity,
                    factoryCapacity = factoryCapacity,
                    cycles = cycles
                )
            }

            0x01 -> {
                // Page 0x01: BMS temperatures (6 probes + MOS temp)
                val temps = mutableListOf<Double>()
                for (i in 0 until 7) {
                    val offset = base + 2 + i * 2
                    if (ensureRange(data, offset, 2)) {
                        val raw = ByteUtils.getSignedShortLE(data, offset)
                        // Temperature is in 0.1°C units
                        temps.add(raw / 10.0)
                    }
                }
                if (temps.isNotEmpty()) {
                    bmsTemperatures[bmsIndex] = temps
                }
            }

            0x02, 0x03, 0x04, 0x05, 0x06 -> {
                val cells = bmsCellPages.getOrPut(bmsIndex) { DoubleArray(MAX_BMS_CELLS) }
                val startCell = (pageNum - 0x02) * 7
                for (i in 0 until 7) {
                    val offset = base + 2 + i * 2
                    if (ensureRange(data, offset, 2)) {
                        val cellIndex = startCell + i
                        if (cellIndex < MAX_BMS_CELLS) {
                            cells[cellIndex] = ByteUtils.getUnsignedShortLE(data, offset) / 1000.0
                        }
                    }
                }
            }
        }
    }

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

    /**
     * Returns the current BMS data snapshots for all detected battery packs.
     * Each entry represents one BMS unit (typically 1 or 2 for dual-battery wheels).
     * Data is accumulated from frame types 0xF1/0xF2 pages 0x00 (summary), 0x01 (temperatures),
     * and 0x02-0x06 (cell voltages).
     */
    override fun getBMSData(): List<BMSData> {
        val allIndices =
            (bmsSummary.keys + bmsTemperatures.keys + bmsCellPages.keys).distinct().sorted()
        return allIndices.map { index ->
            val summary = bmsSummary[index]
            val temps = bmsTemperatures[index]
            val cells = bmsCellPages[index]?.asList()?.filter { it > 0.0 }?.ifEmpty { null }
            BMSData(
                bmsIndex = index,
                voltage = summary?.voltage,
                current = summary?.current,
                remainingCapacity = summary?.remainingCapacity,
                factoryCapacity = summary?.factoryCapacity,
                cycles = summary?.cycles,
                temperatures = temps,
                cellVoltages = cells,
                isCharging = resolveBmsChargingState(summary?.current, lastKnownIsCharging)
            )
        }
    }

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

    private fun estimateBatteryPercent(voltage: Double): Int {
        val fromVoltage = seriesCellsForVoltage(voltage)
        // Latch the largest pack class seen so a deeply discharged 84 V pack is not
        // later mistaken for a full 67 V one.
        if (fromVoltage != null && fromVoltage > (inferredSeriesCells ?: 0)) {
            inferredSeriesCells = fromVoltage
        }
        val series = seriesCellsForModel(lastKnownModel) ?: inferredSeriesCells ?: return 0
        return batteryPercentFromVoltage(voltage, series)
    }

    private fun processFrame(frame: ByteArray) {
        val parsed = parseFrame(frame)
        parsed?.let { outbox.push(ProtocolOutput.Telemetry(it)) }

        if (frame.size >= FRAME_LENGTH) {
            val headerIdx = run {
                for (i in 0..(frame.size - 2)) {
                    if (frame[i] == header[0] && frame[i + 1] == header[1]) return@run i
                }
                -1
            }
            if (headerIdx >= 0 && frame.size - headerIdx >= FRAME_LENGTH) {
                val messageType = ByteUtils.getUnsignedByte(frame, headerIdx + OFFSET_MESSAGE_TYPE)
                if (messageType == FRAME_TYPE_A4) {
                    val reply = frame.copyOfRange(headerIdx, headerIdx + FRAME_LENGTH)
                    reply[16] = 0x98.toByte()
                    reply[2] = 0x01.toByte()
                    outbox.push(ProtocolOutput.Write(reply))
                }
            }
        }
    }

    override fun onNotification(data: ByteArray) {
        byteParser.appendAndExtract(data).forEach(::processFrame)
    }

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

    private fun isValidPassword(value: String): Boolean =
        value.length == 4 && value.all { it in '0'..'9' }

    override fun createCommand(commandType: CommandType, value: CommandValue): ByteArray {
        return when (commandType) {
            CommandType.SET_PASSWORD, CommandType.CHANGE_PASSWORD, CommandType.REMOVE_PASSWORD -> {
                val change = value as? PasswordChangeRequest
                val password = if (commandType == CommandType.CHANGE_PASSWORD) {
                    change?.newPassword
                } else {
                    (value as? CommandValue.Text)?.value
                } ?: return byteArrayOf()
                if (!isValidPassword(password) ||
                    (commandType == CommandType.CHANGE_PASSWORD &&
                        (change == null || !isValidPassword(change.oldPassword)))
                ) return byteArrayOf()
                buildLegacyCommand(
                    command = if (commandType == CommandType.REMOVE_PASSWORD) 0x42 else 0x41
                ).also { frame ->
                    password.forEachIndexed { index, digit -> frame[index + 2] = digit.code.toByte() }
                    if (commandType == CommandType.CHANGE_PASSWORD) {
                        change!!.oldPassword.forEachIndexed { index, digit ->
                            frame[index + 6] = digit.code.toByte()
                        }
                    }
                }
            }
            CommandType.AUTHENTICATE -> {
                val pin = (value as? CommandValue.Text)?.value ?: return byteArrayOf()
                if (pin.length != 4 || pin.any { it !in '0'..'9' }) return byteArrayOf()
                buildLegacyCommand(command = 0x44).also { frame ->
                    pin.forEachIndexed { index, digit -> frame[index + 2] = digit.code.toByte() }
                }
            }

            CommandType.LOCK, CommandType.UNLOCK -> {
                run {
                    if (securityState.authentication == AuthenticationState.REQUIRED) {
                        return byteArrayOf()
                    }
                    if (commandType == CommandType.LOCK) {
                        unlockChallenge = null
                        buildLegacyCommand(command = 0x5D, payload2 = 1)
                    } else {
                        val challenge = unlockChallenge ?: return byteArrayOf()
                        val x = unlockRandom.nextInt(10)
                        val y = unlockRandom.nextInt(10)
                        val z = unlockRandom.nextInt(10)
                        // KingSong mixes the 5F challenge digits with three nonce digits.
                        val sum = x + y + z
                        val a = (sum + challenge[0] + challenge[1] + challenge[2]) % 10
                        val b = (sum + a + challenge[1] + challenge[2]) % 10
                        val c = (sum + a + b + challenge[2]) % 10
                        buildLegacyCommand(command = 0x5D).also { frame ->
                            intArrayOf(a, x, b, y, c, z).forEachIndexed { index, digit ->
                                frame[10 + index] = (0x30 + digit).toByte()
                            }
                        }
                    }
                }
            }

            CommandType.REQUEST_LOCK_STATE -> buildLegacyCommand(command = 0x5E)
            CommandType.LIGHT_ON -> buildLegacyCommand(
                command = 0x73,
                payload2 = 0x12,
                payload3 = 0x01
            )

            CommandType.LIGHT_OFF -> buildLegacyCommand(
                command = 0x73,
                payload2 = 0x13,
                payload3 = 0x01
            )

            CommandType.SET_LIGHT_MODE -> {
                val mode = (value as? CommandValue.Integer)?.value?.coerceIn(0, 2) ?: return byteArrayOf()
                val wireMode = when (mode) {
                    0 -> 0x13
                    1 -> 0x12
                    else -> 0x14
                }
                buildLegacyCommand(command = 0x73, payload2 = wireMode, payload3 = 0x01)
            }

            CommandType.BEEP -> buildLegacyCommand(command = 0x88)
            CommandType.POWER_OFF -> buildLegacyCommand(command = 0x40)
            CommandType.SET_PEDALS_MODE -> {
                val pedalsMode = (value as? CommandValue.Integer)?.value?.coerceIn(0, 2) ?: return byteArrayOf()
                buildLegacyCommand(
                    command = 0x87,
                    payload2 = pedalsMode,
                    payload3 = 0xE0,
                    payload17 = 0x15
                )
            }

            CommandType.SET_LED_MODE -> {
                val ledMode = (value as? CommandValue.Integer)?.value?.coerceIn(0, 0xFF) ?: return byteArrayOf()
                buildLegacyCommand(command = 0x6C, payload2 = ledMode)
            }

            CommandType.LIGHT_BRIGHTNESS -> {
                val intVal = (value as? CommandValue.Integer)?.value ?: return byteArrayOf()
                val mode = when {
                    intVal <= 0 -> 0
                    intVal >= 100 -> 2
                    else -> 1
                }
                val wireMode = when (mode) {
                    0 -> 0x13
                    1 -> 0x12
                    else -> 0x14
                }
                buildLegacyCommand(command = 0x73, payload2 = wireMode, payload3 = 0x01)
            }

            CommandType.SET_SPEED_LIMIT -> {
                // KingSong uses a combined command (0x85) that sets alarms + max speed together.
                // SET_SPEED_LIMIT updates the max speed while preserving current alarm values.
                val maxSpeed = (value as? CommandValue.Integer)?.value?.coerceIn(0, 100) ?: return byteArrayOf()
                buildAlarmSpeedCommand(
                    alarm1 = lastKnownAlarm1Speed ?: 0,
                    alarm2 = lastKnownAlarm2Speed ?: 0,
                    alarm3 = lastKnownAlarm3Speed ?: 0,
                    maxSpeed = maxSpeed
                )
            }

            CommandType.SET_ALARM_SPEED -> {
                val speeds = (value as? CommandValue.Integers)?.copyValues() ?: return byteArrayOf()
                if (speeds.size < 3) return byteArrayOf()
                buildAlarmSpeedCommand(
                    alarm1 = speeds[0].coerceIn(0, 100),
                    alarm2 = speeds[1].coerceIn(0, 100),
                    alarm3 = speeds[2].coerceIn(0, 100),
                    maxSpeed = lastKnownWheelMaxSpeed ?: 0
                )
            }

            CommandType.CALIBRATE -> buildLegacyCommand(command = 0x89)
            CommandType.REQUEST_SERIAL -> buildLegacyCommand(command = 0x63)
            CommandType.REQUEST_FIRMWARE -> buildLegacyCommand(command = 0x9B)

            CommandType.REQUEST_BMS_SERIAL -> buildBmsQuery(type = 0xE1)

            CommandType.SET_LED_STROBE -> {
                val mode = (value as? CommandValue.Integer)?.value?.and(0xFF) ?: return byteArrayOf()
                buildLegacyCommand(command = 0x53, payload2 = mode)
            }

            CommandType.SET_CHARGE_LIMIT -> {
                // Charge cutoff percentage 0..100.
                // Wire: opcode 0x8A, sub-byte 0x09 at offset 2, value u16 LE at offsets 4..5.
                val pct = (value as? CommandValue.Integer)?.value?.coerceIn(0, 100) ?: return byteArrayOf()
                buildWheelParamCommand(subByte = 0x09, value16 = pct)
            }

            CommandType.SET_STANDBY_DELAY -> {
                // Idle auto-poweroff delay in seconds.
                // Wire: opcode 0x3F, sub-byte 0x01 at offset 2, value u16 LE at offsets 4..5.
                val seconds = (value as? CommandValue.Integer)?.value?.coerceIn(0, 65535) ?: return byteArrayOf()
                buildStandbyCommand(seconds = seconds)
            }

            CommandType.SET_PEDAL_CUTOFF_ANGLE -> {
                // Pedal cutoff lean angle in tenths of a degree (unsigned).
                // Wire: opcode 0x8A, sub-byte 0x03 at offset 2, value u16 LE at offsets 4..5.
                val tenths = (value as? CommandValue.Integer)?.value?.coerceIn(0, 65535) ?: return byteArrayOf()
                buildWheelParamCommand(subByte = 0x03, value16 = tenths)
            }

            CommandType.SET_PEDAL_PITCH_TRIM -> {
                // Pedal pitch trim in tenths of a degree (signed, two's complement).
                // Wire: opcode 0x8A, sub-byte 0x01 at offset 2, value u16 LE at offsets 4..5.
                val tenths = (value as? CommandValue.Integer)?.value?.coerceIn(-32768, 32767) ?: return byteArrayOf()
                val raw = if (tenths < 0) tenths + 0x10000 else tenths
                buildWheelParamCommand(subByte = 0x01, value16 = raw)
            }

            CommandType.CUSTOM -> (value as? CommandValue.Bytes)?.copyBytes() ?: byteArrayOf()

            else -> byteArrayOf()
        }
    }

    private fun buildAlarmSpeedCommand(
        alarm1: Int,
        alarm2: Int,
        alarm3: Int,
        maxSpeed: Int
    ): ByteArray {
        val data = byteArrayOf(
            0xAA.toByte(), 0x55.toByte(), 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x85.toByte(), 0x14, 0x5A, 0x5A
        )
        data[2] = alarm1.toByte()
        data[4] = alarm2.toByte()
        data[6] = alarm3.toByte()
        data[8] = maxSpeed.toByte()
        return data
    }

    /**
     * Build a WHEEL_PARAM command (opcode 0x8A).
     *
     * Layout: AA 55 [subByte] 00 [value_lo] [value_hi] 00 ... 8A 14 5A 5A
     *
     * Used for charge limit (sub 0x09), pedal cutoff angle (sub 0x03), and
     * pedal pitch trim (sub 0x01). The 16-bit value is little-endian at
     * offsets 4..5.
     */
    private fun buildWheelParamCommand(subByte: Int, value16: Int): ByteArray {
        val data = byteArrayOf(
            0xAA.toByte(), 0x55.toByte(), 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x8A.toByte(), 0x14, 0x5A, 0x5A
        )
        data[2] = subByte.toByte()
        data[4] = (value16 and 0xFF).toByte()
        data[5] = ((value16 shr 8) and 0xFF).toByte()
        return data
    }

    /**
     * Build a STANDBY command (opcode 0x3F).
     *
     * Layout: AA 55 01 00 [seconds_lo] [seconds_hi] 00 ... 3F 14 5A 5A
     */
    private fun buildStandbyCommand(seconds: Int): ByteArray {
        val data = byteArrayOf(
            0xAA.toByte(), 0x55.toByte(), 0x01, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x3F, 0x14, 0x5A, 0x5A
        )
        data[4] = (seconds and 0xFF).toByte()
        data[5] = ((seconds shr 8) and 0xFF).toByte()
        return data
    }

    /**
     * Build a BMS query frame. Per the KingSong spec, BMS request frames use a zeroed
     * trailer (offsets 17..19 = 0x00) instead of the standard 0x14 0x5A 0x5A.
     */
    private fun buildBmsQuery(type: Int): ByteArray {
        val data = ByteArray(20)
        data[0] = 0xAA.toByte()
        data[1] = 0x55.toByte()
        data[16] = type.toByte()
        // Trailer bytes intentionally left as 0x00.
        return data
    }

    private fun buildLegacyCommand(
        command: Int,
        payload2: Int = 0x00,
        payload3: Int = 0x00,
        payload17: Int = 0x14
    ): ByteArray {
        val data = byteArrayOf(
            0xAA.toByte(), 0x55.toByte(), 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
            0x00, 0x14, 0x5A, 0x5A
        )
        data[2] = payload2.toByte()
        data[3] = payload3.toByte()
        data[16] = command.toByte()
        data[17] = payload17.toByte()
        return data
    }

    override fun getPollingPlan(): ProtocolPollingPlan {
        return ProtocolPollingPlan(
            enabled = true,
            startupQueries = listOf(
                ProtocolQuerySpec(
                    "ks.request-name-version",
                    CommandType.REQUEST_FIRMWARE,
                    maxRetries = 3
                ),
                ProtocolQuerySpec(
                    "ks.request-serial",
                    CommandType.REQUEST_SERIAL,
                    initialDelayMs = 200L,
                    maxRetries = 3
                ),
                ProtocolQuerySpec(
                    QUERY_ID_REQUEST_ALARMS,
                    CommandType.CUSTOM,
                    CommandValue.Bytes(buildLegacyCommand(command = 0x98)),
                    initialDelayMs = 400L,
                    maxRetries = 2
                ),
                // Retain the existing delayed 0x5E query; its dedicated status reply is 0x5F.
                ProtocolQuerySpec(
                    "ks.start-stream",
                    CommandType.REQUEST_LOCK_STATE,
                    initialDelayMs = 2_500L,
                    responseTimeoutMs = 500L,
                    maxRetries = 1
                )
            ),
            periodicQueries = listOf(
                // Keep-alive: a 0x00 ping sent every ~1 s sustains the telemetry stream.
                // Without it, KingSong firmware stops transmitting after the initial burst.
                // eucplanet's keepAlive() sends the same 20-byte 0x00 frame at 1 Hz.
                ProtocolQuerySpec(
                    "ks.keep-alive",
                    CommandType.CUSTOM,
                    CommandValue.Bytes(buildLegacyCommand(command = 0x00)),
                    intervalMs = 1_000L,
                    responseTimeoutMs = 500L,
                    maxRetries = 0
                )
            )
        )
    }

    override fun matchesQueryResponse(query: ProtocolQuerySpec, data: ByteArray): Boolean {
        if (data.size < FRAME_LENGTH) return false
        val headerIdx = run {
            for (i in 0..(data.size - 2)) {
                if (data[i] == header[0] && data[i + 1] == header[1]) return@run i
            }
            -1
        }
        if (headerIdx < 0 || data.size - headerIdx < FRAME_LENGTH) return false
        val messageType = ByteUtils.getUnsignedByte(data, headerIdx + 16)
        return when (query.commandType) {
            CommandType.REQUEST_FIRMWARE -> messageType == FRAME_TYPE_BB
            CommandType.REQUEST_SERIAL -> messageType == FRAME_TYPE_B3
            CommandType.REQUEST_LOCK_STATE -> messageType == 0x5F
            CommandType.CUSTOM -> when (query.id) {
                QUERY_ID_REQUEST_ALARMS ->
                    messageType == FRAME_TYPE_A4 || messageType == FRAME_TYPE_B5
                // Keep-alive / stream-start have no dedicated reply: any live
                // telemetry frame proves the stream is flowing.
                else -> messageType == FRAME_TYPE_A9 || messageType == FRAME_TYPE_B9
            }
            else -> false
        }
    }

    override fun isDeviceReady(data: EUCData): Boolean {
        val tempOk = data.temperature < 75.0
        val voltageOk = data.voltage > 40.0
        val batteryOk = data.batteryLevel >= 5
        return voltageOk && tempOk && batteryOk
    }
}