BleBackend.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.integration

import io.github.tritbool.euc.ble.core.ProtocolSelection
import io.github.tritbool.euc.ble.exceptions.BLEException
import io.github.tritbool.euc.ble.models.EUCData
import io.github.tritbool.euc.ble.models.EUCDevice
import io.github.tritbool.euc.ble.protocols.EUCProtocol
import io.github.tritbool.euc.ble.core.EucUuid

sealed interface BleBackendEvent {
    data object ScanStarted : BleBackendEvent
    data class DeviceDiscovered(val device: EUCDevice) : BleBackendEvent
    data class ScanCompleted(val devices: List<EUCDevice>) : BleBackendEvent
    data class Connected(val device: EUCDevice?) : BleBackendEvent
    data object Connecting : BleBackendEvent
    data object Disconnected : BleBackendEvent
    data class ServicesDiscovered(val serviceUuids: List<EucUuid>) : BleBackendEvent
    data class MtuChanged(val mtu: Int) : BleBackendEvent
    data class ProtocolSelectionRequired(val protocols: List<EUCProtocol>) : BleBackendEvent
    data class ProtocolSelected(val selection: ProtocolSelection) : BleBackendEvent
    data class DataReceived(val data: EUCData) : BleBackendEvent
    /**
     * Event emitted when a raw BLE frame is received.
     * The payload is a defensive copy to ensure immutability for consumers.
     */
    class RawFrameReceived(payload: ByteArray) : BleBackendEvent {
        // Defensive copy keeps event payload immutable for consumers.
        val payload: ByteArray = payload.copyOf()

        override fun equals(other: Any?): Boolean {
            if (this === other) return true
            if (other !is RawFrameReceived) return false
            return payload.contentEquals(other.payload)
        }

        override fun hashCode(): Int = payload.contentHashCode()
    }
    /**
     * Event emitted when an error occurs in the BLE backend.
     */
    data class Error(val error: BLEException) : BleBackendEvent
}

/**
 * Listener interface for receiving BLE backend events.
 */
fun interface BleBackendListener {
    /**
     * Called when a BLE backend event occurs.
     *
     * @param event The event that occurred
     */
    fun onEvent(event: BleBackendEvent)
}