EucProtocolSpec.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.models.BMSData
import io.github.tritbool.euc.ble.models.DiagnosticLogTransfer
import io.github.tritbool.euc.ble.models.EUCData
import io.github.tritbool.euc.ble.models.WheelSecurityState
import io.github.tritbool.euc.ble.core.EucUuid

/**
 * Specifies a single GATT service requirement within a [GattSignature].
 *
 * A service spec matches when:
 * - The service UUID is present in the discovered GATT services.
 * - All [requiredCharacteristicUUIDs] are present as characteristics of that service.
 * - None of the [excludedCharacteristicUUIDs] are present as characteristics of that service.
 *
 * @param uuid The service UUID that must be present.
 * @param requiredCharacteristicUUIDs Characteristic UUIDs that must ALL be present in the service.
 * @param excludedCharacteristicUUIDs Characteristic UUIDs that must NOT be present in the service.
 */
data class GattServiceSpec(
    val uuid: EucUuid,
    val version:Int = 1,
    val requiredCharacteristicUUIDs: Set<EucUuid> = emptySet(),
    val excludedCharacteristicUUIDs: Set<EucUuid> = emptySet(),
)

/**
 * A GATT signature is a list of [GattServiceSpec] entries that all must match for a protocol to
 * be identified by GATT fingerprinting. All specs use AND semantics (every spec must hold).
 *
 * A protocol can declare multiple alternative signatures (OR semantics between signatures):
 * the protocol matches if at least one signature matches.
 */
typealias GattSignature = List<GattServiceSpec>

/**
 * Platform-independent, I/O-free part of a protocol contract: identification, GATT layout,
 * command encoding, polling plan and pure state queries. Shared by flow-compatible facades
 * and the synchronous [SyncEucProtocol].
 */
interface EucProtocolSpec {
    /** Stable fingerprint key; independent of runtime class names and inheritance. */
    val protocolId: String get() = manufacturer

    /** More specific dialect/family implementations may refine this protocol identity. */
    val parentProtocolId: String? get() = null
    /**
     * Manufacturer name (used for display and logging).
     */
    val manufacturer: String

    fun getSecurityState(): WheelSecurityState? = null

    /** Clears connection-specific state without closing this reusable protocol. */
    fun resetSession() {}

    /** Rechecked by the BLE write queue immediately before submission. */
    fun canSendCommand(payload: ByteArray): Boolean = true

    /** Called only after the BLE stack accepts a queued write, not when it is encoded. */
    fun onCommandSubmitted(payload: ByteArray) {}

    /** Whether a BLE-stack rejection may be retried. Accepted writes are never replayed. */
    fun canRetryCommand(payload: ByteArray): Boolean = true

    /** True when this telemetry contains a new speed measurement rather than a carried-over value. */
    fun hasSpeedMeasurement(data: EUCData): Boolean = false

    /**
     * Returns the candidate data characteristic UUIDs for this protocol.
     *
     * Most protocols expose a single data characteristic. Protocols that dynamically detect their
     * dialect (such as InMotion V1/V2) should override this to return all possible candidates so
     * that BLE notifications are enabled for each characteristic at connection time.
     */
    fun getCandidateDataCharacteristicUUIDs(): List<EucUuid> = listOf(getDataCharacteristicUUID())

    /**
     * Get the UUID for the data characteristic
     */
    fun getDataCharacteristicUUID(): EucUuid

    /**
     * Get the UUID for the service
     */
    fun getServiceUUID(): EucUuid

    /**
     * Encode a command. Returns an owned byte array, or an empty array when unsupported,
     * invalid or blocked by protocol state. The session must surface an empty result as failure.
     */
    fun createCommand(commandType: CommandType, value: CommandValue = CommandValue.None): ByteArray

    /** Latest model/dialect snapshot. Conditional encoding still requires protocol state checks. */
    fun getCommandDescriptors(): List<CommandDescriptor> = CommandCatalogue.getCommands(protocolId)

    /** Open-ID encoder extension point; existing protocols retain their enum encoder. */
    fun createCommand(commandId: String, value: CommandValue = CommandValue.None): ByteArray {
        val type = CommandType.entries.firstOrNull { it.name == commandId } ?: return byteArrayOf()
        return createCommand(type, value)
    }

    /** Additional live prerequisites; explanations must never include input values or credentials. */
    fun commandStateError(commandId: String): String? = null

    /**
     * Checked contract API. Rejects invalid values before encoding (and its possible side effects),
     * instead of relying on legacy clamping, masking or ignored fields.
     */
    fun encodeCommand(commandId: String, value: CommandValue = CommandValue.None): CommandEncodingResult {
        val descriptor = getCommandDescriptors().firstOrNull { it.id == commandId }
            ?: return CommandEncodingResult.Rejected(CommandRejection.UNKNOWN_COMMAND, "Command is not advertised")
        if (descriptor.encoding == CommandEncoding.UNAVAILABLE || descriptor.encoding == CommandEncoding.UNKNOWN) {
            return CommandEncodingResult.Rejected(CommandRejection.UNAVAILABLE, "Command is unavailable in this context")
        }
        if (descriptor.input is CommandInput.Unsupported) {
            return CommandEncodingResult.Rejected(
                CommandRejection.UNSUPPORTED_INPUT, descriptor.input.reason
            )
        }
        descriptor.input.validationError(value)?.let {
            return CommandEncodingResult.Rejected(CommandRejection.INVALID_VALUE, it)
        }
        commandStateError(commandId)?.let {
            return CommandEncodingResult.Rejected(CommandRejection.UNAVAILABLE, it)
        }
        val payload = createCommand(commandId, value)
        return if (payload.isNotEmpty()) CommandEncodingResult.Encoded(payload)
        else CommandEncodingResult.Rejected(CommandRejection.ENCODING_FAILED, "Protocol state prevented encoding")
    }

    /**
     * Explicit command support matrix for this protocol.
     * Commands outside this set are considered unsupported by design.
     */
    val supportedCommandTypes: Set<CommandType>
        get() = emptySet()

    /**
     * API-level command support check (used by framework and clients).
     */
    fun getCommandSupport(commandType: CommandType): CommandSupport {
        return if (supportedCommandTypes.contains(commandType)) {
            CommandSupport.SUPPORTED
        } else {
            CommandSupport.UNSUPPORTED
        }
    }

    /**
     * Returns true if the given BLE device advertisement name suggests this protocol.
     *
     * Used as a secondary selection signal when GATT fingerprinting is ambiguous or
     * unavailable (e.g. protocols that share a common service UUID). The default
     * implementation returns false; protocols with a recognizable device-name pattern
     * should override this and match their known advertised names or model keywords.
     */
    fun matchesDeviceName(deviceName: String): Boolean = false

    /**
     * Optional polling/query plan consumed by the session layer.
     */
    fun getPollingPlan(): ProtocolPollingPlan = ProtocolPollingPlan.disabled()

    /**
     * Optional query/response matcher used by session observability and retry policy.
     */
    fun matchesQueryResponse(query: ProtocolQuerySpec, data: ByteArray): Boolean = false

    /**
     * Get the UUID for the write characteristic (if different from data characteristic)
     */
    fun getWriteCharacteristicUUID(): EucUuid = getDataCharacteristicUUID()

    /**
     * Preferred GATT write type for commands sent by this protocol.
     *
     * The default [ProtocolWriteType.AUTO] lets the BLE layer derive the write type from the
     * properties advertised by the write characteristic. Protocols whose wheels require a specific
     * write type (for example Gotway/Begode serial-to-BLE bridges, which only accept
     * write-without-response on FFE1) should override this.
     */
    val preferredWriteType: ProtocolWriteType get() = ProtocolWriteType.AUTO

    /**
     * Check if the device is ready for operation
     */
    fun isDeviceReady(data: EUCData): Boolean

    /**
     * Get BMS (Battery Management System) data for this protocol.
     * Returns null if this protocol does not support BMS data extraction.
     * Protocols that support BMS data should override this method to return
     * a list of BMSData objects representing the current state of all battery packs.
     */
    fun getBMSData(): List<BMSData>? = null

    /**
     * Latest diagnostic-log download snapshot, or `null` if none was started (or unsupported).
     * Data is only exposed once the whole file is received and CRC-verified.
     */
    fun getDiagnosticLogTransfer(): DiagnosticLogTransfer? = null
}

/**
 * Preferred GATT write type declared by a protocol for its command writes.
 */
enum class ProtocolWriteType {
    /** Derive the write type from the GATT properties advertised by the characteristic. */
    AUTO,

    /** Prefer write-with-response (WRITE_TYPE_DEFAULT). */
    WITH_RESPONSE,

    /** Prefer write-without-response (WRITE_TYPE_NO_RESPONSE). */
    NO_RESPONSE
}

/**
 * Standard command types for EUCs
 */
enum class CommandType {
    LIGHT_ON,
    LIGHT_OFF,
    SET_LIGHT_MODE,
    LIGHT_BRIGHTNESS,
    /** Set the high beam independently from the low beam (LeaperKim two-frame binary command). */
    SET_HIGH_BEAM,
    /** InMotion V9: daytime running light, value = Boolean. */
    SET_DRL,
    /** InMotion V9: imperial speed units (true) instead of metric (false), value = Boolean. */
    SET_IMPERIAL_UNITS,
    /** InMotion V9: mute the speaker (true) or re-enable it (false), value = Boolean. */
    SET_MUTE,
    /** InMotion V9: AVAS wave sound (true) or off (false), value = Boolean. */
    SET_AVAS,
    SPEAKER_VOLUME,
    BEEP,
    POWER_OFF,
    LOCK,
    UNLOCK,
    SET_PEDALS_MODE,
    SET_LED_MODE,
    SET_LED_STROBE,
    SET_SPEED_LIMIT,
    SET_ALARM_SPEED,
    CALIBRATE,
    REQUEST_SERIAL,
    REQUEST_FIRMWARE,
    REQUEST_BATTERY_INFO,
    REQUEST_BMS_SERIAL,
    RESET_TRIP,
    /** LeaperKim: pedal zero-point tilt offset, value = tenths of a degree (signed Int). */
    SET_PEDAL_ANGLE,
    /** LeaperKim: ride-mode scalar 0..100, value = Int. */
    SET_RIDE_MODE,
    /** InMotion: pedal sensitivity of the active ride mode 0..100 %, value = Int. */
    SET_PEDAL_SENSITIVITY,
    /** LeaperKim: maximum PWM percentage 0..100, value = Int. */
    SET_PWM_LIMIT,
    /** KingSong: charge cutoff percentage 0..100, value = Int. */
    SET_CHARGE_LIMIT,
    /** KingSong: idle auto-poweroff delay in seconds, value = Int. */
    SET_STANDBY_DELAY,
    /** KingSong: pedal cutoff lean angle in tenths of a degree, value = Int. */
    SET_PEDAL_CUTOFF_ANGLE,
    /** KingSong: pedal pitch trim in tenths of a degree (signed), value = Int. */
    SET_PEDAL_PITCH_TRIM,
    /** KingSong: exactly four ASCII digits as a String, preserving leading zeros. */
    AUTHENTICATE,
    /** KingSong: new password as exactly four ASCII digits (String). */
    SET_PASSWORD,
    /** KingSong: [PasswordChangeRequest] with old and new four-ASCII-digit passwords. */
    CHANGE_PASSWORD,
    /** KingSong: current password as exactly four ASCII digits (String). */
    REMOVE_PASSWORD,
    /** KingSong: request notification-confirmed lock status (0x5E -> 0x5F). */
    REQUEST_LOCK_STATE,
    /**
     * Start downloading the wheel diagnostic log (InMotion P6/V9). Poll progress and the
     * verified file with [EucProtocolSpec.getDiagnosticLogTransfer].
     */
    REQUEST_DIAGNOSTIC_LOG,
    /** Cancel an active diagnostic-log download and close the wheel-side file. */
    CANCEL_DIAGNOSTIC_LOG,
    CUSTOM
}

enum class CommandSupport {
    SUPPORTED,
    UNSUPPORTED
}

data class ProtocolQuerySpec(
    val id: String,
    val commandType: CommandType,
    val value: CommandValue = CommandValue.None,
    val initialDelayMs: Long = 0L,
    val intervalMs: Long = 0L,
    val responseTimeoutMs: Long = 1500L,
    val maxRetries: Int = 2,
    val retryBackoffMs: Long = 500L
)

data class ProtocolPollingPlan(
    val enabled: Boolean,
    val startupQueries: List<ProtocolQuerySpec> = emptyList(),
    val periodicQueries: List<ProtocolQuerySpec> = emptyList()
) {
    companion object {
        fun disabled() = ProtocolPollingPlan(enabled = false)
    }
}