GotwaySyncProtocol.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.frames.FixedSizeFrameParser
import io.github.tritbool.euc.ble.models.BMSData
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

/**
 * Gotway EUC Protocol Implementation
 * Supports Gotway series electric unicycles
 */


/**
 * Gotway/Begode reverse-engineered protocol (updated)
 *
 * This comment summarizes the observed variants:
 *  - Raw "A" / "B" frames (controller serial stream, header 0x55 0xAA)
 *  - Short "legacy" packets (e.g., 0x01 / 0x02) re-emitted by some adapters
 *  - Type 0xA5 packets (compressed commands/status emitted by firmware/adapters)
 *
 * General observations:
 *  - Raw A/B frames observed on the serial port typically use header 0x55 0xAA
 *    and Big Endian (BE) fields for 16/32 bit integers.
 *  - Legacy packets (0x01/0x02) and some 0xA5 packets often use Little Endian (LE)
 *    encoding and a more compact format.
 *  - Current/temperature fields can be signed; must be converted correctly.
 *  - Many firmware/adapters do not add checksum. The stream can be fragmented,
 *    delayed, or lose bytes on the BLE side (no flow control).
 *  - Some packets include BMS cell voltages at the end, encoded as pairs of 2 bytes (LE)
 *    or in mV/centivolts depending on the variant.
 *
 * Example (observed):
 *   A: 55 AA 19 F0 00 00 00 00 00 00 01 2C FD CA 00 01 FF F8 00 18 5A 5A 5A 5A
 *   B: 55 AA 00 0A 4A 12 48 00 1C 20 00 2A 00 03 00 07 00 08 04 18 5A 5A 5A 5A
 *
 * Summary format (adjust according to firmware/model):
 *  - Frame A (header 0x55 0xAA):
 *      Bytes 0-1:  0x55 0xAA
 *      Bytes 2-3:  BE voltage (fixed point, e.g., 1/100)
 *      Bytes 4-5:  BE speed (fixed point, e.g., 3.6 * value / 100 -> km/h)
 *      Bytes 6-9:  BE distance (uint32, meters)
 *      Bytes 10-11: BE current (signed, fixed point)
 *      Bytes 12-13: BE temperature (signed or raw MPU value)
 *      Bytes 14-17: unknown / flags
 *      Byte 18:    frame type (e.g., 0x00)
 *      Byte 19:    footer (0x18)
 *      Bytes 20-..: footer 0x5A 0x5A 0x5A 0x5A (or variants) + optional BMS trailing
 *
 *  - Frame B (header 0x55 0xAA):
 *      Bytes 2-5:  BE total distance (uint32)
 *      Byte 6:     pedals mode / alarms (nibbles)
 *      Bytes 7-12: additional unknown fields
 *      Byte 13:    LED / mode
 *      Bytes 14-17: unknown
 *      Byte 18:    frame type (e.g., 0x04)
 *      Footer same
 *
 *  - Legacy packets (e.g., 0x01 / 0x02):
 *      - Often sent by Serial->BLE adapter or alternative firmware.
 *      - LE fields, more compact formats; can represent voltage/speed/etc.
 *
 *  - 0xA5 packets:
 *      - Used for commands (LIGHT_ON/OFF, BEEP, POWER_OFF) and sometimes for compressed states.
 *        Different structure (header 0xA5 ...).
 *
 * Parsing recommendations:
 *  - Dispatch by first byte/header: 0x55 (A/B raw), 0x01/0x02 (legacy), 0xA5 (command/status),
 *    or by type byte in the frame if present.
 *  - For A/B: process integers as BE. For legacy/0xA5: try LE.
 *  - Handle fragmentation: tolerate variable sizes, ignore too short frames,
 *    attempt re-synchronization on 0x55 0xAA or adapter headers.
 *  - Dynamically extract cell voltages from the queue if present:
 *      read pairs of 2 bytes (LE) and convert to V (mV -> V or /100 -> V depending on ranges).
 *  - Correctly convert signed values (current, motor temperatures).
 *  - Stay defensive: validate plausible ranges (voltage, current, temperature).
 *
 * Why were these variants not in the old comment?
 *  - The original comment described the raw serial stream observed on a specific controller/firmware.
 *    Other firmware/adapters (Serial->BLE) re-emit or transform these bytes
 *    (different headers, different endianness) — these variants were not necessarily
 *    present during the initial reverse engineering.
 */
open class GotwaySyncProtocol(
    private val clock: EucClock,
) : SyncEucProtocol {


    data class BatteryVoltageRange(
        val minVoltage: Double,
        val maxVoltage: Double,
    ) {
        val seriesCells: Int
            get() = (maxVoltage / 4.2).toInt()
    }


    companion object {
        const val FRAME_SIZE = 24
        val HEADER: ByteArray = BLEConstants.GOTWAY_FRAME_HEADER
        val FOOTER: ByteArray = BLEConstants.GOTWAY_FRAME_FOOTER
        private const val MIN_BATTERY_VOLTAGE = 52.0
        private const val MAX_BATTERY_VOLTAGE = 134.4
        private const val MAX_BMS_CELL_SLOTS = 56
        private val FIRMWARE_PREFIXES = listOf("GW", "JN", "CF", "BF")
        private val WRAPPED_METADATA_FIRST_BYTES =
            setOf('N'.code, 'G'.code, 'J'.code, 'C'.code, 'B'.code)

        /** Conversion factor for wheels that have been set to imperial units by the
         *  Begode app. When the imperial flag is set in a Type-B frame the wheel
         *  transmits speed in mph and trip distance in miles on every subsequent
         *  Type-A frame; we multiply by this constant to convert back to km/h and
         *  km so all downstream consumers always receive metric values. */
        private const val MILES_TO_KM = 1.60934

        /** Delay before writing a confirmation beep after a settings-change command with no
         *  ack/checksum, matching legacy WheelLog's `sendCommand(s, "b", 100)` default. */
        private const val BEEP_FOLLOWUP_DELAY_MS = 100L

        private enum class BoardTemperatureEncoding {
            UNKNOWN,
            TENTHS_OF_CELSIUS,
            MPU6050_RAW,
        }

        private val begodeBatteryVoltages: Map<String, BatteryVoltageRange> = mapOf(

            // ─────────────────────────────────────────────────────────────────────
            // BEGODE — 50S — plateforme tres haute tension 210 V
            // Charge complète : 210,0 V ; borne basse électrochimique : 150,0 V
            // ─────────────────────────────────────────────────────────────────────
            "race" to BatteryVoltageRange(150.0, 210.0),

            // ─────────────────────────────────────────────────────────────────────
            // BEGODE — 40S — plateforme haute tension 168 V
            // Charge complète : 168,0 V ; borne basse électrochimique : 120,0 V
            // ─────────────────────────────────────────────────────────────────────
            "Blitz Pro" to BatteryVoltageRange(120.0, 168.0),
            "ET Max" to BatteryVoltageRange(120.0, 168.0),
            "Panther" to BatteryVoltageRange(120.0, 168.0),
            "X-Way Pro" to BatteryVoltageRange(120.0, 168.0),

            // ─────────────────────────────────────────────────────────────────────
            // BEGODE — 32S — plateforme 134 V / charge complète 134,4 V
            // ─────────────────────────────────────────────────────────────────────
            "Blitz" to BatteryVoltageRange(96.0, 134.4),
            "Extreme" to BatteryVoltageRange(96.0, 134.4),
            "EX30" to BatteryVoltageRange(96.0, 134.4),
            "EX30 Pro" to BatteryVoltageRange(96.0, 134.4),
            "Master" to BatteryVoltageRange(96.0, 134.4),
            "Master V2" to BatteryVoltageRange(96.0, 134.4),
            "Master V3" to BatteryVoltageRange(96.0, 134.4),
            "Master V4" to BatteryVoltageRange(96.0, 134.4),
            "Master Pro" to BatteryVoltageRange(96.0, 134.4),
            "Master Pro V2" to BatteryVoltageRange(96.0, 134.4),
            "Master Pro V3" to BatteryVoltageRange(96.0, 134.4),
            "Master X" to BatteryVoltageRange(96.0, 134.4),
            "T4 Pro" to BatteryVoltageRange(96.0, 134.4),
            "X-Way" to BatteryVoltageRange(96.0, 134.4),

            // ─────────────────────────────────────────────────────────────────────
            // BEGODE — 24S — plateforme 100 V / charge complète 100,8 V
            // ─────────────────────────────────────────────────────────────────────
            "Falcon" to BatteryVoltageRange(72.0, 100.8),
            "Falcon Pro" to BatteryVoltageRange(72.0, 100.8),
            "T4" to BatteryVoltageRange(72.0, 100.8),
            "T4 Max" to BatteryVoltageRange(72.0, 100.8),
            "T4 Pro Max" to BatteryVoltageRange(72.0, 100.8),
            "Hero" to BatteryVoltageRange(72.0, 100.8),
            "Hero V2" to BatteryVoltageRange(72.0, 100.8),
            "Hero V3" to BatteryVoltageRange(72.0, 100.8),
            "EX" to BatteryVoltageRange(72.0, 100.8),
            "EX.N" to BatteryVoltageRange(72.0, 100.8),
            "EXN" to BatteryVoltageRange(72.0, 100.8),
            "EX20S" to BatteryVoltageRange(72.0, 100.8),
            "EX20" to BatteryVoltageRange(72.0, 100.8),
            "Nikola Plus" to BatteryVoltageRange(72.0, 100.8),
            "Nikola Plus AR+" to BatteryVoltageRange(72.0, 100.8),
            "Nikola AR+" to BatteryVoltageRange(72.0, 100.8),
            "RS" to BatteryVoltageRange(72.0, 100.8),
            "RS HS" to BatteryVoltageRange(72.0, 100.8),
            "RS HT" to BatteryVoltageRange(72.0, 100.8),
            "RS C38" to BatteryVoltageRange(72.0, 100.8),
            "RS C30" to BatteryVoltageRange(72.0, 100.8),
            "Monster Pro" to BatteryVoltageRange(72.0, 100.8),
            "Monster Pro V2" to BatteryVoltageRange(72.0, 100.8),

            // ─────────────────────────────────────────────────────────────────────
            // BEGODE — 20S — plateforme 84 V / charge complète 84,0 V
            // ─────────────────────────────────────────────────────────────────────
            "A2" to BatteryVoltageRange(60.0, 84.0),
            "Mten4" to BatteryVoltageRange(60.0, 84.0),
            "Mten5" to BatteryVoltageRange(60.0, 84.0),
            "Mten3" to BatteryVoltageRange(60.0, 84.0),
            "MCM5" to BatteryVoltageRange(60.0, 84.0),
            "MCM5 V2" to BatteryVoltageRange(60.0, 84.0),
            "Tesla" to BatteryVoltageRange(60.0, 84.0),
            "Tesla V2" to BatteryVoltageRange(60.0, 84.0),
            "Tesla V3" to BatteryVoltageRange(60.0, 84.0),
            "T3" to BatteryVoltageRange(60.0, 84.0),
            "Nikola" to BatteryVoltageRange(60.0, 84.0),
            "Nikola 84V" to BatteryVoltageRange(60.0, 84.0),
            "MSX" to BatteryVoltageRange(60.0, 84.0),
            "MSuper X" to BatteryVoltageRange(60.0, 84.0),
            "MSuper Pro" to BatteryVoltageRange(60.0, 84.0),

            // ─────────────────────────────────────────────────────────────────────
            // BEGODE — 10S — plateforme 42 V / charge complète 42,0 V
            // ─────────────────────────────────────────────────────────────────────
            "Future" to BatteryVoltageRange(30.0, 42.0),

            // ─────────────────────────────────────────────────────────────────────
            // EXTREME BULL — 40S — plateforme 168 V / charge complète 168,0 V
            // ─────────────────────────────────────────────────────────────────────
            "Rocket" to BatteryVoltageRange(120.0, 168.0),
            "Commander GT Pro" to BatteryVoltageRange(120.0, 168.0),
            "Commander GT Pro+" to BatteryVoltageRange(120.0, 168.0),
            "Commander GT Pro Plus" to BatteryVoltageRange(120.0, 168.0),

            // ─────────────────────────────────────────────────────────────────────
            // EXTREME BULL — 36S — plateforme 151,2 V
            // Annoncée commercialement à « 151 V ».
            // ─────────────────────────────────────────────────────────────────────
            "Griffin" to BatteryVoltageRange(108.0, 151.2),

            // ─────────────────────────────────────────────────────────────────────
            // EXTREME BULL — 35S — plateforme 147 V
            // ─────────────────────────────────────────────────────────────────────
            "K6" to BatteryVoltageRange(105.0, 147.0),

            // ─────────────────────────────────────────────────────────────────────
            // EXTREME BULL — 32S — plateforme 134 V / charge complète 134,4 V
            // ─────────────────────────────────────────────────────────────────────
            "Commander Mini" to BatteryVoltageRange(96.0, 134.4),
            "Commander Pro" to BatteryVoltageRange(96.0, 134.4),
            "Commander Pro 50E" to BatteryVoltageRange(96.0, 134.4),
            "Commander Pro 50S" to BatteryVoltageRange(96.0, 134.4),
            "Commander GT" to BatteryVoltageRange(96.0, 134.4),

            // ─────────────────────────────────────────────────────────────────────
            // EXTREME BULL — 24S — plateforme 100 V / charge complète 100,8 V
            // ─────────────────────────────────────────────────────────────────────
            "Commander" to BatteryVoltageRange(72.0, 100.8),
        )

    }

    private val frameParser = FixedSizeFrameParser(FRAME_SIZE, HEADER, FOOTER)
    private val outbox = ProtocolOutbox()
    private val logger = object {
        fun debug(tag: String, message: String) {
            outbox.push(ProtocolOutput.DebugLog(tag, message))
        }
    }
    private val pendingWrites = mutableMapOf<String, ByteArray>()
    private var nextTimerId = 0L

    private var hasSeenType7Pwm = false

    //private val scope = CoroutineScope(Dispatchers.IO)
    private var lastKnownVoltage: Double? = null
    private var lastKnownCurrent: Double? = null
    private var hasType1Voltage = false
    private var hasType7Current = false
    private var lastKnownSpeed = 0.0
    private var lastKnownTemperature = 0.0
    private var lastKnownTripDistance = 0.0
    private var lastKnownTotalDistance: Double? = null
    private var lastKnownMotorTemperature: Double? = null
    private var lastKnownPwm: Double? = null
    private var lastKnownModel: String? = null
    private var lastKnownFirmwareVersion: String? = null

    private var lastKnownPhaseCurrent: Double? = null

    private var boardTemperatureEncoding = BoardTemperatureEncoding.UNKNOWN
    private var gotwayFirmwareVariant: String? = null
    private var useHwPwm = false
    // Guarded by this instance's monitor via processFrame, getBMSData and close.
    // Cell pages are keyed by BMS stream (Type 2 = 0, Type 3 = 1); each stream carries
    // the cells of two consecutive groups (G1+G2, G3+G4). All other maps are keyed by
    // group index 0..3, matching the Type 1 subpage byte.
    private val smartBmsCellPages: MutableMap<Int, DoubleArray> = mutableMapOf()
    private val smartBmsStreamPageCounts: MutableMap<Int, Int> = mutableMapOf()
    private val smartBmsTemperatures: MutableMap<Int, Array<Double?>> = mutableMapOf()
    private val smartBmsCurrents: MutableMap<Int, Double> = mutableMapOf()
    private val smartBmsGroupVoltages: MutableMap<Int, Double> = mutableMapOf()

    /** True when the wheel has reported imperial-units mode via bit 0 of the Type-B
     *  settings word. Latched on every Type-B frame and applied to speed and distance
     *  fields so EUCData always exposes km/h and km. */
    private var wheelInMiles = false

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

    /**
     * The advertised firmware banner selects which catalogue profile applies. Stock firmware gets
     * the base command set; "BF" (SmirnoV) adds the fourth pedal mode and "CF" (Freestyl3r) adds
     * the fourth alarm preset. Until a banner arrives the base set is used, so unknown wheels are
     * never offered a command their firmware is not known to accept.
     */
    override fun getCommandDescriptors(): List<CommandDescriptor> =
        CommandCatalogue.getCommands(protocolId, CommandContext(resolveModelName(), gotwayFirmwareVariant))

    override fun getServiceUUID(): UUID = UUID.fromString(BLEConstants.GOTWAY_SERVICE_UUID)
    override fun getDataCharacteristicUUID(): UUID =
        UUID.fromString(BLEConstants.GOTWAY_READ_CHARACTERISTIC)

    /**
     * Gotway/Begode wheels use an HM-10 style serial-to-BLE bridge whose FFE1 characteristic only
     * advertises write-without-response; legacy WheelLog also writes every Gotway command with
     * WriteType.WITHOUT_RESPONSE.
     */
    override val preferredWriteType: ProtocolWriteType = ProtocolWriteType.NO_RESPONSE

    override fun resetSession() {
        frameParser.reset()
        outbox.clear()
        pendingWrites.clear()
        smartBmsCellPages.clear()
        smartBmsStreamPageCounts.clear()
        smartBmsTemperatures.clear()
        smartBmsCurrents.clear()
        smartBmsGroupVoltages.clear()
        lastKnownVoltage = null
        lastKnownCurrent = null
        hasType1Voltage = false
        hasType7Current = false
        lastKnownSpeed = 0.0
        lastKnownTemperature = 0.0
        lastKnownTripDistance = 0.0
        lastKnownTotalDistance = null
        lastKnownMotorTemperature = null
        lastKnownPwm = null
        lastKnownModel = null
        lastKnownFirmwareVersion = null
        lastKnownPhaseCurrent = null
        gotwayFirmwareVariant = null
        useHwPwm = false
        hasSeenType7Pwm = false
        boardTemperatureEncoding = BoardTemperatureEncoding.UNKNOWN
        wheelInMiles = false
    }

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

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

    private fun processFrame(frame: ByteArray) {
        val eucData = when (frame.getOrNull(18)?.toInt()?.and(0xFF)) {
            0x00 -> parseTypeA(frame)
            0x01 -> {
                parseType1(frame)
                null
            }

            0x02 -> {
                parseType2or3(frame, streamIndex = 0)
                null
            }

            0x03 -> {
                parseType2or3(frame, streamIndex = 1)
                null
            }

            0x04 -> parseTypeB(frame)
            0x07 -> parseType7(frame)
            // SmirnoV firmware tuning frame (tag 0xFF): discard without parsing.
            // eucplanet explicitly discards this with a log line; our else branch
            // would silently drop it too, but an explicit case improves observability.
            0xFF -> null
            else -> null // Ignore unknown frame types from the reassembler
        }

        eucData?.let { outbox.push(ProtocolOutput.Telemetry(it)) }
    }

    override fun hasSpeedMeasurement(data: EUCData): Boolean = data.frameType == "Type A"

    private fun parseTypeA(data: ByteArray): EUCData? {

        val speedRaw = ByteUtils.tryGetSignedShortBE(data, 4)?.toInt() ?: return null
        val rawSpeed = abs((speedRaw * 3.6) / 100.0)
        // Apply imperial conversion: when the Begode app is set to mph the wheel
        // transmits speed in mph on the wire even though the spec says km/h. Multiply
        // by MILES_TO_KM so all downstream consumers always receive km/h.
        val speed = if (wheelInMiles) rawSpeed * MILES_TO_KM else rawSpeed
        if (abs(speed) > 200.0) return null  // frame corrompue ou sentinel

        val voltageRaw = ByteUtils.tryGetUnsignedShortBE(data, 2) ?: return null
        val fallbackVoltage = voltageRaw / 100.0
        val voltage = lastKnownVoltage ?: fallbackVoltage
        if (!hasType1Voltage) {
            // Before the dedicated Type 1 battery-voltage frame is seen, keep tracking
            // voltage from Type A so Type B/Type 7 carry-forward telemetry remains usable.
            lastKnownVoltage = fallbackVoltage
        }
        if (voltage > 300.0) return null  // pareil pour voltage

        val frameVariant = ByteUtils.tryGetUnsignedByte(data, 19)
        val rawTripDistanceKm = when (frameVariant) {
            0x18 -> ByteUtils.tryGetUnsignedShortBE(data, 8)?.toDouble()?.div(1000.0)
            else -> ByteUtils.tryGetUnsignedIntBE(data, 6)?.toDouble()?.div(1000.0)
        } ?: return null
        // Apply imperial conversion to distance as well.
        val tripDistanceKm =
            if (wheelInMiles) rawTripDistanceKm * MILES_TO_KM else rawTripDistanceKm
        val currentRaw = ByteUtils.tryGetSignedShortBE(data, 10) ?: return null

        // phaseCurrent: courant moteur, toujours positif (valeur absolue en A)
        val phaseCurrent = abs(currentRaw / 100.0)
        lastKnownPhaseCurrent = phaseCurrent

        // current: courant batterie, signé (négatif = régén)
        // Reste l'offset 10 comme fallback jusqu'à ce que Type 7 arrive.
        // IMPORTANT: on met à jour lastKnownCurrent SANS abs, signe préservé.
        if (!hasType7Current) {
            lastKnownCurrent = currentRaw / 100.0
        }
        val current = lastKnownCurrent ?: (currentRaw / 100.0)
        val tempRaw = ByteUtils.tryGetSignedShortBE(data, 12) ?: return null
        val temperature = decodeBoardTemperature(tempRaw.toInt())
        lastKnownSpeed = speed
        lastKnownTemperature = temperature

        val rawPwmA = ByteUtils.tryGetSignedShortBE(data, 14) ?: 0
        val pwmFromTypeA = if (useHwPwm) {
            abs(rawPwmA.toDouble())
        } else {
            abs(rawPwmA.toDouble()) / 10.0
        }

// Fallback uniquement tant qu'aucune vraie PWM Type 7 n'a été observée.
        if (!hasSeenType7Pwm) {
            lastKnownPwm = if (pwmFromTypeA in 0.0..100.0) pwmFromTypeA else null
        }

        val power = voltage * current
        val batteryLevel = estimateBatteryLevel(voltage)
        lastKnownTripDistance = tripDistanceKm

        return EUCData(
            frameType = "Type A",
            speed = speed,
            voltage = voltage,
            current = current,
            temperature = temperature,
            batteryLevel = batteryLevel,
            distance = tripDistanceKm,
            power = power,
            pwm = lastKnownPwm,
            timestamp = clock.currentTimeMillis(),
            rawData = data,
            manufacturer = manufacturer,
            model = resolveModelName(),
            serialNumber = null,
            firmwareVersion = lastKnownFirmwareVersion ?: gotwayFirmwareVariant,
            isCharging = false, // Not available in this frame
            rideTime = 0,
            cellVoltages = getCombinedCellVoltages(),
            motorTemperature = lastKnownMotorTemperature,
            totalDistance = lastKnownTotalDistance,
            phaseCurrent = lastKnownPhaseCurrent
        )
    }

    private fun parseTypeB(data: ByteArray): EUCData? {
        val distanceRaw = ByteUtils.tryGetUnsignedIntBE(data, 2) ?: return null
        val settings = ByteUtils.tryGetUnsignedShortBE(data, 6)
        // Legacy WheelLog maps firmware pedals bits with "2 - raw" before exposing the
        // mode value to the app layer (typically mapped into 0..2); keep this behavior
        // for compatibility with existing consumers.
        val pedalsMode = settings?.let { 2 - ((it shr 13) and 0x03) }
        val alarmMode = settings?.let { (it shr 10) and 0x03 }
        val rollAngleMode = settings?.let { (it shr 7) and 0x03 }
        val usesMiles = settings?.let { (it and 0x01) == 1 }
        // Latch the imperial flag so parseTypeA can convert speed/distance on every
        // subsequent frame without repeating the detection logic there.
        wheelInMiles = usesMiles == true
        // Bytes 8-9 are the auto-sleep countdown *remaining*, expressed in seconds, and not a
        // configured delay in minutes. Real WheelLog captures prove it: the field ticks down
        // exactly one unit per wall-clock second while the wheel is idle, is refreshed back to
        // 7200 while riding, and never exceeds 7200 (= 120 min). Forwarding the raw value broke
        // the EUCData.autoPowerOffMinutes contract and made the UI show impossible settings such
        // as "7170 min"; divide by 60 the same way LeaperkimSyncProtocol already does.
        val autoPowerOffSeconds = ByteUtils.tryGetUnsignedShortBE(data, 8)
        val autoPowerOffMinutes = autoPowerOffSeconds?.let { it / 60 }
        // Sentinel raised from 100 to 200: modern high-speed wheels (Master Pro, XWay,
        // MSX HS) legitimately set tiltback thresholds above 100 km/h, so the old
        // `< 100` guard incorrectly discarded valid settings for those models.
        val tiltBackSpeed = ByteUtils.tryGetUnsignedShortBE(data, 10)?.takeIf { it < 200 }
        val ledMode = ByteUtils.tryGetUnsignedByte(data, 13)
        val alertFlags = ByteUtils.tryGetUnsignedByte(data, 14)
        val lightMode = ByteUtils.tryGetUnsignedByte(data, 15)?.and(0x03)
        val wheelAlarm = alertFlags?.let { (it and 0x01) == 1 }

        val rawTotalDistance = distanceRaw.toDouble() / 1000.0
        lastKnownTotalDistance =
            if (wheelInMiles) rawTotalDistance * MILES_TO_KM else rawTotalDistance
        val voltage = lastKnownVoltage ?: 0.0
        val current = lastKnownCurrent ?: 0.0
        val power = voltage * current
        val batteryLevel = estimateBatteryLevel(voltage)

        return EUCData(
            frameType = "Type B",
            speed = lastKnownSpeed,
            voltage = voltage,
            current = current,
            temperature = lastKnownTemperature,
            batteryLevel = batteryLevel,
            distance = lastKnownTripDistance,
            power = power,
            pwm = lastKnownPwm,
            timestamp = clock.currentTimeMillis(),
            rawData = data,
            manufacturer = manufacturer,
            model = resolveModelName(),
            serialNumber = null,
            firmwareVersion = lastKnownFirmwareVersion ?: gotwayFirmwareVariant,
            isCharging = false,
            rideTime = 0,
            cellVoltages = null,
            motorTemperature = null,
            totalDistance = lastKnownTotalDistance,
            pedalsMode = pedalsMode,
            alarmMode = alarmMode,
            rollAngleMode = rollAngleMode,
            usesMiles = usesMiles,
            autoPowerOffMinutes = autoPowerOffMinutes,
            tiltBackSpeed = tiltBackSpeed,
            // The tiltback is the max speed SET_SPEED_LIMIT writes: same value, normalized field.
            wheelMaxSpeed = tiltBackSpeed,
            ledMode = ledMode,
            lightMode = lightMode,
            alertFlags = alertFlags,
            wheelAlarm = wheelAlarm,
            phaseCurrent = lastKnownPhaseCurrent
        )
    }

    private fun parseType1(data: ByteArray) {
        val batteryVoltageTenth = ByteUtils.tryGetUnsignedShortBE(data, 6) ?: return
        lastKnownVoltage = batteryVoltageTenth / 10.0
        hasType1Voltage = true

        val bmsSubpage = ByteUtils.tryGetUnsignedByte(data, 19) ?: return
        if (bmsSubpage !in 0..3) return
        val firstTemperature = ByteUtils.tryGetSignedShortBE(data, 10) ?: return
        val secondTemperature = ByteUtils.tryGetSignedShortBE(data, 12) ?: return
        val groupVoltage = ByteUtils.tryGetSignedShortBE(data, 14) ?: return
        val current = ByteUtils.tryGetSignedShortBE(data, 8) ?: return
        // Type 1 subpages address the four smart-BMS groups directly (Begode app G1..G4):
        // each subpage carries its own group voltage, current and its two temperature probes.
        val groupIndex = bmsSubpage
        val temperatures = smartBmsTemperatures.getOrPut(groupIndex) { arrayOfNulls(2) }
        temperatures[0] = firstTemperature.toDouble()
        temperatures[1] = secondTemperature.toDouble()
        smartBmsCurrents[groupIndex] = current / 10.0
        smartBmsGroupVoltages[groupIndex] = groupVoltage / 10.0
    }

    private fun parseType2or3(data: ByteArray, streamIndex: Int) {
        val page = ByteUtils.tryGetUnsignedByte(data, 19) ?: return
        val cells = smartBmsCellPages.getOrPut(streamIndex) { DoubleArray(MAX_BMS_CELL_SLOTS) }
        val pageCount = page + 1
        if (pageCount > (smartBmsStreamPageCounts[streamIndex] ?: 0)) {
            smartBmsStreamPageCounts[streamIndex] = pageCount
        }
        for (i in 0 until 8) {
            val cellRaw = ByteUtils.tryGetUnsignedShortBE(data, (i + 1) * 2) ?: continue
            val cellIndex = page * 8 + i
            if (cellIndex in cells.indices) {
                cells[cellIndex] = cellRaw / 1000.0
            }
        }
    }

    private fun parseType7(data: ByteArray): EUCData? {
        val batteryCurrentRaw = ByteUtils.tryGetSignedShortBE(data, 2) ?: return null
        val motorTemperatureRaw = ByteUtils.tryGetSignedShortBE(data, 6) ?: return null
        val truePwmRaw = ByteUtils.tryGetSignedShortBE(data, 8)

        // WheelLog/Begode Type 7 convention: positive raw value means charge/regen, so
        // published battery current is inverted to match discharge-positive telemetry.
        lastKnownCurrent = (-batteryCurrentRaw) / 100.0
        hasType7Current = true
        // Begode/WheelLog convention: a zero motor-temperature reading means the wheel
        // has no motor temperature sensor; never clear the last known reading on zero,
        // otherwise the value flickers between frames.
        if (motorTemperatureRaw != 0.toShort()) lastKnownMotorTemperature = motorTemperatureRaw.toDouble()
        truePwmRaw?.let { raw ->
            // Type 7 = vraie PWM entière en %, Begode partage le PWM réel (pas calculé).[web:23][file:16]
            val truePwmAbs = kotlin.math.abs(raw.toDouble())

            // 0 < PWM ≤ 100 => valeur valide.
            if (truePwmAbs in 0.0..100.0) {
                lastKnownPwm = truePwmAbs
                hasSeenType7Pwm = true
            }
            // Sinon (0 ou hors plage) => on ne change pas lastKnownPwm, et on NE met PAS PWM à 46 % random.
        }

        val voltage = lastKnownVoltage ?: 0.0
        val current = lastKnownCurrent ?: 0.0
        val power = voltage * current

        return EUCData(
            frameType = "Type 7",
            speed = lastKnownSpeed,
            voltage = voltage,
            current = current,
            temperature = lastKnownTemperature,
            batteryLevel = estimateBatteryLevel(voltage),
            distance = lastKnownTripDistance,
            power = power,
            pwm = lastKnownPwm,
            timestamp = clock.currentTimeMillis(),
            rawData = data,
            manufacturer = manufacturer,
            model = resolveModelName(),
            serialNumber = null,
            firmwareVersion = lastKnownFirmwareVersion ?: gotwayFirmwareVariant,
            isCharging = false,
            rideTime = 0,
            cellVoltages = getCombinedCellVoltages(),
            motorTemperature = lastKnownMotorTemperature,
            totalDistance = lastKnownTotalDistance,
            phaseCurrent = lastKnownPhaseCurrent
        )
    }

    private fun estimateBatteryLevel(voltage: Double): Int {
        return if (voltage <= 0.0) 0
        else {
            val battSpecs = lastKnownModel
                ?.let { model ->
                    begodeBatteryVoltages.entries.firstOrNull { entry ->
                        entry.key.equals(model, ignoreCase = true)
                    }?.value
                }
            if (battSpecs != null) (((voltage - battSpecs.minVoltage) / (battSpecs.maxVoltage - battSpecs.minVoltage)) * 100.0)
                .toInt()
                .coerceIn(0, 100)
            else
                (((voltage - MIN_BATTERY_VOLTAGE) / (MAX_BATTERY_VOLTAGE - MIN_BATTERY_VOLTAGE)) * 100.0)
                    .toInt()
                    .coerceIn(0, 100)
        }
    }

    private fun decodeBoardTemperature(tempRaw: Int): Double {
        val legacyTenths = tempRaw / 10.0
        val mpu6050 = (tempRaw / 340.0) + 36.53

        when (boardTemperatureEncoding) {
            BoardTemperatureEncoding.TENTHS_OF_CELSIUS -> return legacyTenths
            BoardTemperatureEncoding.MPU6050_RAW -> return mpu6050
            BoardTemperatureEncoding.UNKNOWN -> Unit
        }

        if (tempRaw < -1_360 || tempRaw > 1_250) {
            boardTemperatureEncoding = BoardTemperatureEncoding.MPU6050_RAW
            return mpu6050
        }

        // Valeur réellement impossible en dixièmes de °C, mais le seuil précédent
        // devrait déjà couvrir ce cas. Garde ce garde-fou pour les évolutions futures.
        if (legacyTenths !in -20.0..80.0 && mpu6050 in -20.0..80.0) {
            boardTemperatureEncoding = BoardTemperatureEncoding.MPU6050_RAW
            return mpu6050
        }

        // L’encodage reste inconnu. Préférer le format historique direct évite de
        // transformer 25,0 °C (250) en 37,27 °C arbitrairement.
        return legacyTenths
    }

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

    private fun decodeBegodeEncodedName(data: ByteArray): String {
        // Format Begode 0x10+char : UNIQUEMENT valide si le paquet est
        // constitué EXCLUSIVEMENT de paires 0x10+char (hors premier byte de longueur éventuel).
        // On vérifie d'abord que tous les bytes non-nuls suivent ce pattern.
        // Un paquet "EXTREME" = 7 chars = 14 bytes de paires 0x10+char,
        // éventuellement précédés d'un byte de taille.
        val start = if (data.size % 2 != 0 && data[0].toInt().and(0xFF) == data.size - 1) 1 else 0
        val slice = data.drop(start)
        // Valider que TOUS les bytes pairs sont 0x10 et impairs sont printable ASCII
        if (slice.size < 6) return ""
        if (slice.size % 2 != 0) return ""
        for (i in slice.indices step 2) {
            val prefix = slice[i].toInt().and(0xFF)
            val char = slice[i + 1].toInt().and(0xFF)
            if (prefix != 0x10) return ""
            if (char !in 0x20..0x7E) return ""
        }
        val result = slice.filterIndexed { i, _ -> i % 2 == 1 }
            .map { it.toInt().and(0xFF).toChar() }
            .joinToString("")
            .trim()
        logger.debug("GotwayASCII", "decodeBegodeEncodedName: decoded='$result'")
        return result
    }

    private fun startsWithFrameHeader(data: ByteArray): Boolean {
        return data.size >= 2 && data[0] == HEADER[0] && data[1] == HEADER[1]
    }

    private fun parseDirectMetadataMessage(message: String): String? {
        return when {
            message.startsWith("NAME", ignoreCase = true) -> message
            FIRMWARE_PREFIXES.any { message.startsWith(it, ignoreCase = true) } -> message
            else -> null
        }
    }

    private fun extractWrappedMetadataMessage(data: ByteArray): String? {
        if (!startsWithFrameHeader(data) || data.size <= 2) return null
        val payload = data.copyOfRange(2, data.size)
        val firstByte = payload.first().toInt() and 0xFF

        if (firstByte in WRAPPED_METADATA_FIRST_BYTES) {
            parseDirectMetadataMessage(payload.decodeToString().trim())?.let { return it }
        }

        if (payload.size > 1 && payload[0] == 0x10.toByte()) {
            // Some wrapped metadata responses arrive as 55 AA + 0x10 marker + ASCII payload.
            // Accept that specific shim to preserve the pre-regression name/firmware retrieval path.
            parseDirectMetadataMessage(
                payload.copyOfRange(1, payload.size).decodeToString().trim()
            )?.let {
                return it
            }
        }

        if (firstByte != 0x10) return null

        val begodeDecoded = decodeBegodeEncodedName(payload)
        return if (begodeDecoded.isNotEmpty()) "NAME$begodeDecoded" else null
    }

    private fun isFirmwareMetadataMessage(message: String?): Boolean {
        return message?.let {
            FIRMWARE_PREFIXES.any { prefix -> it.startsWith(prefix, ignoreCase = true) }
        } == true
    }

    private fun parseLegacyAsciiMetadata(data: ByteArray) {
        if (data.isEmpty()) return

        logger.debug(
            "GotwayASCII",
            "parseLegacyAsciiMetadata: rawSize=${data.size} first5=${
                data.take(5).map { ByteUtils.byteToHex(it) }
            }"
        )

        // Tentative 1 : décodage ASCII direct (GW/JN/CF/BF et NAME standard)
        val directMessage = data.decodeToString().trim()

        val message: String = parseDirectMetadataMessage(directMessage)
            ?: extractWrappedMetadataMessage(data)
            ?: run {
                if (startsWithFrameHeader(data)) return

                // Tentative 2 : décodage format Begode 0x10+char
                // Seulement si le paquet est structurellement 100% du format 0x10+char
                val begodeDecoded = decodeBegodeEncodedName(data)
                if (begodeDecoded.isNotEmpty()) "NAME$begodeDecoded"
                else {
                    logger.debug(
                        "GotwayASCII",
                        "parseLegacyAsciiMetadata: UNRECOGNIZED direct='$directMessage'"
                    )
                    return
                }
            }

        logger.debug("GotwayASCII", "parseLegacyAsciiMetadata: PARSED message='$message'")

        when {
            message.startsWith("NAME", ignoreCase = true) -> {
                val name = message.substringAfter("NAME", "").trimStart(':', ' ').trim()
                if (name.isNotEmpty()) {
                    logger.debug(
                        "GotwayASCII",
                        "parseLegacyAsciiMetadata: MODEL found name='$name'"
                    )
                    lastKnownModel = name
                }
            }

            message.startsWith("GW", ignoreCase = true) -> {
                lastKnownFirmwareVersion = message.substring(2).trim().ifEmpty { null }
                gotwayFirmwareVariant = "Begode"
                useHwPwm = false
                logger.debug(
                    "GotwayASCII",
                    "parseLegacyAsciiMetadata: FIRMWARE found variant=Begode version=$lastKnownFirmwareVersion"
                )
            }

            message.startsWith("JN", ignoreCase = true) -> {
                lastKnownFirmwareVersion = message.substring(2).trim().ifEmpty { null }
                gotwayFirmwareVariant = "ExtremeBull"
                useHwPwm = false
                logger.debug(
                    "GotwayASCII",
                    "parseLegacyAsciiMetadata: FIRMWARE found variant=ExtremeBull version=$lastKnownFirmwareVersion"
                )
            }

            message.startsWith("CF", ignoreCase = true) -> {
                lastKnownFirmwareVersion = message.substring(2).trim().ifEmpty { null }
                gotwayFirmwareVariant = "Freestyl3r"
                useHwPwm = true
                logger.debug(
                    "GotwayASCII",
                    "parseLegacyAsciiMetadata: FIRMWARE found variant=Freestyl3r version=$lastKnownFirmwareVersion"
                )
            }

            message.startsWith("BF", ignoreCase = true) -> {
                lastKnownFirmwareVersion = message.substring(2).trim().ifEmpty { null }
                gotwayFirmwareVariant = "SV"
                useHwPwm = true
                logger.debug(
                    "GotwayASCII",
                    "parseLegacyAsciiMetadata: FIRMWARE found variant=SV version=$lastKnownFirmwareVersion"
                )
            }
        }
    }

    private fun resolveModelName(): String {
        lastKnownModel?.let { return it }
        return when (gotwayFirmwareVariant) {
            "Begode" -> "Begode"
            "ExtremeBull" -> "ExtremeBull"
            else -> "Gotway"
        }
    }

    override fun matchesQueryResponse(query: ProtocolQuerySpec, data: ByteArray): Boolean {
        if (data.isEmpty()) return false

        logger.debug(
            "GotwayQueryMatch",
            "matchesQueryResponse: query=${query.commandType} size=${data.size} data=${
                data.take(20).map { ByteUtils.byteToHex(it) }
            }"
        )

        return when (query.commandType) {
            CommandType.REQUEST_SERIAL -> {
                val direct = parseDirectMetadataMessage(data.decodeToString().trim())
                if (direct?.startsWith("NAME", ignoreCase = true) == true) {
                    logger.debug(
                        "GotwayQueryMatch",
                        "matchesQueryResponse: REQUEST_SERIAL matched direct NAME"
                    )
                    return true
                }
                val wrapped = extractWrappedMetadataMessage(data)
                if (wrapped?.startsWith("NAME", ignoreCase = true) == true) {
                    logger.debug(
                        "GotwayQueryMatch",
                        "matchesQueryResponse: REQUEST_SERIAL matched wrapped NAME"
                    )
                    return true
                }
                if (startsWithFrameHeader(data)) return false
                // Begode 0x10+char : valide seulement si le paquet est structurellement pur
                val begodeDecoded = decodeBegodeEncodedName(data)
                val matched = begodeDecoded.isNotEmpty()
                logger.debug(
                    "GotwayQueryMatch",
                    "matchesQueryResponse: REQUEST_SERIAL begodeDecoded='$begodeDecoded' matched=$matched"
                )
                matched
            }

            CommandType.REQUEST_FIRMWARE -> {
                val direct = parseDirectMetadataMessage(data.decodeToString().trim())
                val wrapped = extractWrappedMetadataMessage(data)
                val matched =
                    isFirmwareMetadataMessage(direct) || isFirmwareMetadataMessage(wrapped)
                logger.debug(
                    "GotwayQueryMatch",
                    "matchesQueryResponse: REQUEST_FIRMWARE direct='$direct' wrapped='$wrapped' matched=$matched"
                )
                matched
            }

            else -> false
        }
    }

    /**
     * Schedules a follow-up ASCII command to be written [delayMs] after the primary command
     * returned by [createCommand].
     * Mirrors legacy WheelLog.Android's `Handler().postDelayed(... sendCommand ...)` chains
     * used for Begode/Gotway settings that require more than one character (e.g. a
     * confirmation beep, or a multi-character max-speed/tiltback sequence).
     */
    private fun scheduleWrite(delayMs: Long, bytes: ByteArray) {
        val id = "gotway.write.${nextTimerId++}"
        pendingWrites[id] = bytes
        outbox.push(ProtocolOutput.StartTimer(id, delayMs))
    }

    override fun onTimer(id: String) {
        pendingWrites.remove(id)?.let { outbox.push(ProtocolOutput.Write(it)) }
    }

    /** Schedules a single confirmation beep ('b') after a settings-change command, matching
     *  legacy WheelLog's default `sendCommand(s)` (== `sendCommand(s, "b", 100)`) behavior:
     *  Begode/Gotway settings commands have no ack, so the wheel's beep is the only user
     *  feedback that the change was applied. */
    private fun scheduleConfirmationBeep() {
        scheduleWrite(BEEP_FOLLOWUP_DELAY_MS, "b".encodeToByteArray())
    }

    override fun createCommand(commandType: CommandType, value: CommandValue): ByteArray {
        // Begode/Gotway has no binary command envelope: every control command is a
        // 1-byte ASCII character written without response to the FFE1 characteristic,
        // with no checksum/ack (confirmed via legacy WheelLog.Android's GotwayAdapter
        // and eried/eucplanet's begode.md protocol reference, section 6.1). The
        // previous 0xA5 0x5A "binary" command header used here was fictional and the
        // wheel silently ignored it, which is why BEEP/LIGHT_ON/LIGHT_OFF appeared to
        // do nothing.
        //
        // Several settings commands have no ack/checksum, so legacy WheelLog.Android follows
        // them with a confirmation beep (or, for calibration/max-speed, a short character
        // sequence) written a short delay later. Those follow-up writes are scheduled via
        // [scheduleWrite]/[scheduleConfirmationBeep] as timer actions.
        return when (commandType) {
            CommandType.LIGHT_ON -> {
                scheduleConfirmationBeep()
                "Q".encodeToByteArray()
            }

            CommandType.LIGHT_OFF -> {
                scheduleConfirmationBeep()
                "E".encodeToByteArray()
            }

            CommandType.SET_LIGHT_MODE -> {
                // Begode/Gotway front light has three states (matches legacy WheelLog
                // GotwayAdapter.setLightMode): 0 = off, 1 = on, 2 = strobe.
                val command = when ((value as? CommandValue.Integer)?.value?.coerceIn(0, 2)) {
                    0 -> "E".encodeToByteArray()
                    1 -> "Q".encodeToByteArray()
                    2 -> "T".encodeToByteArray()
                    else -> return byteArrayOf()
                }
                scheduleConfirmationBeep()
                command
            }

            CommandType.SET_PEDALS_MODE -> {
                // ASCII pedal-tightness letters, per the Begode protocol reference: 'h' = hard,
                // 'f' = medium, 's' = soft. 'i' selects the fourth pedal mode, which only exists
                // on SmirnoV custom firmware (advertised banner "BF"); the catalogue hides the
                // option unless that variant was detected.
                //
                // The reported pedals mode is decoded elsewhere as `2 - raw`, which already lands
                // in this same 0=hard .. 2=soft space, so write and read agree.
                val command = when ((value as? CommandValue.Integer)?.value) {
                    0 -> "h".encodeToByteArray()
                    1 -> "f".encodeToByteArray()
                    2 -> "s".encodeToByteArray()
                    3 -> "i".encodeToByteArray()
                    else -> return byteArrayOf()
                }
                scheduleConfirmationBeep()
                command
            }

            CommandType.SET_ALARM_SPEED -> {
                // Begode/Gotway exposes a single alarm-preset selector rather than per-threshold
                // speeds (matches legacy WheelLog GotwayAdapter.updateAlarmMode):
                // 0 = two alarms (30 + 35/45 km/h) + 80% PWM tiltback,
                // 1 = one alarm (35/45 km/h) + 80% PWM tiltback,
                // 2 = 80% PWM tiltback only (no speed alarms),
                // 3 = 'I', the fourth alarm preset added by Freestyl3r custom firmware
                // (advertised banner "CF"); the catalogue hides the option otherwise.
                val command = when ((value as? CommandValue.Integer)?.value) {
                    0 -> "o".encodeToByteArray()
                    1 -> "u".encodeToByteArray()
                    2 -> "i".encodeToByteArray()
                    3 -> "I".encodeToByteArray()
                    else -> return byteArrayOf()
                }
                scheduleConfirmationBeep()
                command
            }

            CommandType.SET_SPEED_LIMIT -> {
                // Max-speed/tiltback-speed setting (matches legacy WheelLog
                // GotwayAdapter.updateMaxSpeed): a short beep, then "W"+"Y" to select the
                // parameter, then the two ASCII digits of the speed in km/h, then a closing
                // double-beep. A value of 0 disables the tiltback speed limit via '"'.
                val maxSpeed = (value as? CommandValue.Integer)?.value ?: return byteArrayOf()
                if (maxSpeed <= 0) {
                    scheduleWrite(100L, "\"".encodeToByteArray())
                    scheduleWrite(200L, "b".encodeToByteArray())
                    scheduleWrite(300L, "b".encodeToByteArray())
                } else {
                    val clamped = maxSpeed.coerceIn(1, 99)
                    val tens = ('0' + (clamped / 10)).toString().encodeToByteArray()
                    val units = ('0' + (clamped % 10)).toString().encodeToByteArray()
                    scheduleWrite(100L, "W".encodeToByteArray())
                    scheduleWrite(200L, "Y".encodeToByteArray())
                    scheduleWrite(300L, tens)
                    scheduleWrite(400L, units)
                    scheduleWrite(500L, "b".encodeToByteArray())
                    scheduleWrite(600L, "b".encodeToByteArray())
                }
                "b".encodeToByteArray()
            }

            CommandType.CALIBRATE -> {
                // Wheel calibration (matches legacy WheelLog GotwayAdapter.wheelCalibration):
                // "c" starts calibration, "y" confirms it ~300ms later.
                scheduleWrite(300L, "y".encodeToByteArray())
                "c".encodeToByteArray()
            }

            CommandType.BEEP -> "b".encodeToByteArray()
            CommandType.REQUEST_SERIAL -> "N".encodeToByteArray()
            CommandType.REQUEST_FIRMWARE -> "V".encodeToByteArray()
            else -> byteArrayOf()
        }
    }

    override fun getPollingPlan(): ProtocolPollingPlan {
        return ProtocolPollingPlan(
            enabled = true,
            startupQueries = listOf(
                ProtocolQuerySpec(
                    // Legacy WheelLog.Android and eried/eucplanet both send a single
                    // 'b' (beep) right after notifications are enabled: it serves as a
                    // UX cue ("the wheel beeped, we're connected") and flushes the
                    // serial-to-BLE bridge's input buffer. There is no response frame
                    // for this command, so it's a fire-and-forget single attempt.
                    id = "gotway.connect-beep",
                    commandType = CommandType.BEEP,
                    initialDelayMs = 0L,
                    responseTimeoutMs = 200L,
                    maxRetries = 0
                ),
                ProtocolQuerySpec(
                    id = "gotway.request-model",
                    commandType = CommandType.REQUEST_SERIAL,
                    initialDelayMs = 1000L,      // laisser la roue finir son burst initial
                    responseTimeoutMs = 2000L,   // les roues Gotway peuvent être lentes
                    maxRetries = 5,
                    retryBackoffMs = 500L
                ),
                ProtocolQuerySpec(
                    id = "gotway.request-firmware",
                    commandType = CommandType.REQUEST_FIRMWARE,
                    initialDelayMs = 1500L,
                    responseTimeoutMs = 2000L,
                    maxRetries = 3,
                    retryBackoffMs = 500L
                )
            ),
            periodicQueries = emptyList()
        )
    }


    override fun isDeviceReady(data: EUCData): Boolean {
        // Conservative readiness checks: p
        return data.voltage > 0 && data.speed >= 0
    }

    /**
     * Returns the current BMS data snapshots for all detected smart-BMS groups.
     * Each entry represents one cell group (up to 4, matching the Begode app's
     * G1..G4 tabs). Group summaries come from Type 1 frames (subpage = group) and
     * cell voltages from the Type 2/3 streams (Type 2 carries groups 1 and 2,
     * Type 3 carries groups 3 and 4).
     */
    override fun getBMSData(): List<BMSData> {
        val groupCount = maxOf(
            maxOf(smartBmsTemperatures.size, smartBmsCurrents.size, smartBmsGroupVoltages.size),
            smartBmsCellPages.size * 2
        )
        return (0 until groupCount).map { groupIndex ->
            val streamIndex = groupIndex / 2
            val streamCells = smartBmsCellPages[streamIndex]?.asList().orEmpty()
            val pages = smartBmsStreamPageCounts[streamIndex] ?: 0
            val halfSize = if (pages > 0) pages * 4 else (streamCells.size + 1) / 2
            val cells = streamCells
                .chunked(halfSize.coerceAtLeast(1))
                .getOrNull(groupIndex % 2)
                ?.filter { it > 0.0 }
                ?.ifEmpty { null }
            val temperatures = smartBmsTemperatures[groupIndex]
                ?.takeIf { it.all { temperature -> temperature != null } }
                ?.filterNotNull()
            BMSData(
                bmsIndex = groupIndex,
                voltage = smartBmsGroupVoltages[groupIndex],
                current = smartBmsCurrents[groupIndex],
                remainingCapacity = null, // Capacity not available in smart BMS pages
                factoryCapacity = null, // Factory capacity not available in smart BMS pages
                cycles = null, // Cycle count not available in smart BMS pages
                temperatures = temperatures,
                cellVoltages = cells,
                isCharging = resolveBmsChargingState(smartBmsCurrents[groupIndex], null)
            )
        }
    }
}