package com.example.cmake_project_test

import android.Manifest
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothGattService
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.bluetooth.le.BluetoothLeScanner
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings
import android.content.Context
import android.content.pm.PackageManager
import android.util.Log
import androidx.core.app.ActivityCompat
import java.util.UUID

/**
 * 蓝牙管理器 - 轻迅协议V1.0.1实现
 * 负责蓝牙设备连接、数据接收和状态管理
 */
class BluetoothManager(private val context: Context) {
    
    // PPTM命令编码器
    private val pptmEncoder = PPTMCommandEncoder()
    
    companion object {
        private const val TAG = "BluetoothManager"
        
        // 轻迅协议相关常量
        object Protocol {
            // 协议版本
            const val VERSION = "1.0.1"
            
            // 数据包格式
            const val PACKET_HEADER_SIZE = 4  // 功能码(2字节) + 数据长度(2字节)
            const val CRC_SIZE = 2            // CRC16校验(2字节)
            const val MIN_PACKET_SIZE = PACKET_HEADER_SIZE + CRC_SIZE
            
            // 功能码定义
            const val FUNC_QUERY_DEVICE_INFO = 0x0000    // 查询设备信息
            const val FUNC_START_COLLECTION = 0x0001     // 开启采集
            const val FUNC_QUERY_BATTERY = 0x0002       // 查询电量
            const val FUNC_SET_SAMPLE_RATE = 0x0003     // 设置采样率
            const val FUNC_SET_GAIN = 0x0004            // 设置增益
            const val FUNC_SET_FILTER = 0x0005          // 设置滤波器
            const val FUNC_SET_LEAD = 0x0006            // 设置导联
            const val FUNC_SET_ALARM = 0x0007          // 设置报警
            const val FUNC_SET_TIME = 0x0008           // 设置时间
            const val FUNC_SET_DATE = 0x0009           // 设置日期
            const val FUNC_POWER_LINE_FILTER = 0x000A  // 工频滤波
            const val FUNC_QUERY_STATUS = 0x000B       // 查询状态
            const val FUNC_RESET_DEVICE = 0x000C       // 设备复位
            const val FUNC_UPDATE_FIRMWARE = 0x000D    // 固件升级
            const val FUNC_DATA_STREAM = 0x8000        // 数据流
            const val FUNC_ALARM_DATA = 0x8001         // 报警数据
            const val FUNC_STATUS_REPORT = 0x8002     // 状态报告
            
            // 数据包类型
            const val PACKET_TYPE_COMMAND = 0x00       // 命令包
            const val PACKET_TYPE_RESPONSE = 0x01      // 响应包
            const val PACKET_TYPE_DATA = 0x02          // 数据包
            const val PACKET_TYPE_ALARM = 0x03         // 报警包
            
            // 采集开关
            const val COLLECTION_OFF = 0x00           // 关闭采集
            const val COLLECTION_ON = 0x01            // 开启采集
            
            // 工频滤波
            const val POWER_LINE_FILTER_OFF = 0x00    // 关闭工频滤波
            const val POWER_LINE_FILTER_ON = 0x01     // 开启工频滤波
            
            // 采样率
            const val SAMPLE_RATE_125 = 125           // 125Hz
            const val SAMPLE_RATE_250 = 250           // 250Hz
            const val SAMPLE_RATE_500 = 500           // 500Hz
            const val SAMPLE_RATE_1000 = 1000         // 1000Hz
            
            // 增益设置
            const val GAIN_1 = 1                      // 1倍增益
            const val GAIN_2 = 2                      // 2倍增益
            const val GAIN_4 = 4                      // 4倍增益
            const val GAIN_8 = 8                      // 8倍增益
            
            // 导联设置
            const val LEAD_I = 0x01                   // I导联
            const val LEAD_II = 0x02                  // II导联
            const val LEAD_III = 0x03                 // III导联
            const val LEAD_AVR = 0x04                 // aVR导联
            const val LEAD_AVL = 0x05                 // aVL导联
            const val LEAD_AVF = 0x06                 // aVF导联
            const val LEAD_V1 = 0x07                  // V1导联
            const val LEAD_V2 = 0x08                  // V2导联
            const val LEAD_V3 = 0x09                  // V3导联
            const val LEAD_V4 = 0x0A                  // V4导联
            const val LEAD_V5 = 0x0B                  // V5导联
            const val LEAD_V6 = 0x0C                  // V6导联
            
            // 响应状态码
            const val RESPONSE_SUCCESS = 0x00         // 成功
            const val RESPONSE_FAILED = 0x01          // 失败
            const val RESPONSE_INVALID_PARAM = 0x02   // 参数无效
            const val RESPONSE_NOT_SUPPORTED = 0x03   // 不支持
            const val RESPONSE_BUSY = 0x04            // 设备忙
            const val RESPONSE_TIMEOUT = 0x05         // 超时
        }
        
        // 常见的ECG设备UUID列表
        private val SERVICE_UUIDS = listOf(
            UUID.fromString("6e400001-b5a3-f393-e0a9-68716563686f"), // Nordic UART Service (NUS) - 你的设备
        )
        
        private val CHARACTERISTIC_UUIDS = listOf(
            UUID.fromString("6e400002-b5a3-f393-e0a9-68716563686f"), // Nordic UART TX Characteristic - 发送数据
        )
        
        // Notify特征UUID列表
        private val NOTIFY_CHARACTERISTIC_UUIDS = listOf(
            UUID.fromString("6e400003-b5a3-f393-e0a9-68716563686f"), // Nordic UART RX Characteristic - 你的设备
        )
        
        // 设备名称前缀 (根据你的设备调整)
        private const val DEVICE_NAME_PREFIX = "ECG"
    }
    
    private var bluetoothManagerService: android.bluetooth.BluetoothManager? = null
    private var bluetoothAdapter: BluetoothAdapter? = null
    private var bluetoothGatt: BluetoothGatt? = null
    private var bluetoothLeScanner: BluetoothLeScanner? = null
    
    // 连接状态
    private var isConnected = false
    private var isConnecting = false
    private var isClassicScanReceiverRegistered = false
    
    // Handler和延迟任务
    private val mainHandler = android.os.Handler(android.os.Looper.getMainLooper())
    private var bleScanStopRunnable: Runnable? = null
    
    // 清理状态标志
    private var isCleaningUp = false
    
    // 设备列表
    private val discoveredDevices = mutableListOf<BluetoothDevice>()
    
    // 当前连接的服务和特征
    private var currentService: BluetoothGattService? = null
    private var currentCharacteristic: BluetoothGattCharacteristic? = null
    private var currentNotifyCharacteristic: BluetoothGattCharacteristic? = null
    
    // 协议状态
    private var deviceInfo: DeviceInfo? = null
    private var isCollecting = false
    private var currentSampleRate = Protocol.SAMPLE_RATE_500
    private var currentGain = Protocol.GAIN_1
    private var currentLead = Protocol.LEAD_II
    private var powerLineFilterEnabled = false
    
    // 数据统计
    private var totalPacketsReceived = 0L
    private var totalBytesReceived = 0L
    private var totalPacketsSent = 0L
    private var totalBytesSent = 0L
    
    // 回调接口
    interface BluetoothCallback {
        fun onDeviceFound(device: BluetoothDevice)
        fun onConnected(device: BluetoothDevice)
        fun onDisconnected()
        fun onDataReceived(data: ByteArray)
        fun onError(message: String)
        fun onStatusChanged(status: String)
        fun onScanComplete(devices: List<BluetoothDevice>)
        fun onCommandSent(success: Boolean, message: String)
        fun onProtocolDataReceived(functionCode: Int, data: ByteArray)
        fun onDeviceInfoReceived(deviceInfo: DeviceInfo)
        fun onBatteryLevelReceived(level: Int)
        fun onCollectionStatusChanged(isCollecting: Boolean)
    }
    
    // 设备信息数据类
    data class DeviceInfo(
        val deviceId: String,
        val firmwareVersion: String,
        val hardwareVersion: String,
        val serialNumber: String,
        val manufacturer: String,
        val model: String,
        val capabilities: List<String>
    )
    
    private var callback: BluetoothCallback? = null
    
    init {
        initializeBluetooth()
    }
    
    /**
     * 初始化蓝牙
     */
    private fun initializeBluetooth() {
        try {
            bluetoothManagerService = context.getSystemService(Context.BLUETOOTH_SERVICE) as android.bluetooth.BluetoothManager
            bluetoothAdapter = bluetoothManagerService?.adapter
            
            if (bluetoothAdapter == null) {
                Log.e(TAG, "设备不支持蓝牙")
                callback?.onError("设备不支持蓝牙")
                return
            }
            
            if (!bluetoothAdapter!!.isEnabled) {
                Log.w(TAG, "蓝牙未启用")
                callback?.onStatusChanged("蓝牙未启用，请先启用蓝牙")
                return
            }
            
            // 初始化BLE扫描器
            bluetoothLeScanner = bluetoothAdapter?.bluetoothLeScanner
            
            if (bluetoothLeScanner == null) {
                Log.w(TAG, "设备不支持BLE")
                callback?.onStatusChanged("设备不支持BLE，将使用传统蓝牙扫描")
            }
            
            Log.d(TAG, "蓝牙初始化成功")
            callback?.onStatusChanged("蓝牙已就绪")
            
        } catch (e: Exception) {
            Log.e(TAG, "蓝牙初始化失败: ${e.message}")
            callback?.onError("蓝牙初始化失败: ${e.message}")
        }
    }
    
    /**
     * 设置回调
     */
    fun setCallback(callback: BluetoothCallback) {
        this.callback = callback
    }
    
    /**
     * 扫描蓝牙设备
     */
    fun startScan() {
        if (bluetoothAdapter == null) {
            callback?.onError("❌ 蓝牙未初始化")
            callback?.onStatusChanged("💡 请检查设备是否支持蓝牙")
            return
        }
        
        if (!bluetoothAdapter!!.isEnabled) {
            callback?.onError("❌ 蓝牙未启用")
            callback?.onStatusChanged("💡 请在系统设置中开启蓝牙")
            return
        }
        
        try {
            // 清空之前的设备列表
            discoveredDevices.clear()
            callback?.onStatusChanged("🔍 开始扫描蓝牙设备...")
            callback?.onStatusChanged("⏱️ 扫描时间: 15秒")
            callback?.onStatusChanged("💡 请确保目标设备:")
            callback?.onStatusChanged("   • 蓝牙已开启")
            callback?.onStatusChanged("   • 设置为可发现模式")
            callback?.onStatusChanged("   • 在10米范围内")
            callback?.onStatusChanged("   • 未与其他设备连接")
            
            // 检查所有必要权限
            val missingPermissions = mutableListOf<String>()
            
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
                missingPermissions.add("BLUETOOTH_SCAN")
            }
            
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                missingPermissions.add("BLUETOOTH_CONNECT")
            }
            
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                missingPermissions.add("ACCESS_FINE_LOCATION")
            }
            
            if (missingPermissions.isNotEmpty()) {
                callback?.onError("❌ 缺少权限: ${missingPermissions.joinToString(", ")}")
                callback?.onStatusChanged("💡 请在应用设置中授予蓝牙和位置权限")
                return
            }
            
            callback?.onStatusChanged("✅ 权限检查通过，开始扫描...")
            
            // 优先使用BLE扫描
            if (bluetoothLeScanner != null) {
                callback?.onStatusChanged("📡 使用BLE扫描模式")
                startBleScan()
            } else {
                // 回退到传统蓝牙扫描
                callback?.onStatusChanged("📡 使用传统蓝牙扫描模式")
                startClassicScan()
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "扫描失败: ${e.message}")
            callback?.onError("❌ 扫描失败: ${e.message}")
            callback?.onStatusChanged("💡 请尝试重启蓝牙或重启设备")
        }
    }
    
    /**
     * 开始BLE扫描
     */
    private fun startBleScan() {
        try {
            val scanSettings = ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
                .setReportDelay(0) // 立即报告结果
                .build()
            
            bluetoothLeScanner?.startScan(null, scanSettings, bleScanCallback)
            Log.d(TAG, "BLE扫描已开始")
            callback?.onStatusChanged("📡 BLE扫描进行中...")
            
            // 取消之前的延迟任务（如果存在）
            bleScanStopRunnable?.let { mainHandler.removeCallbacks(it) }
            
            // 15秒后停止扫描
            bleScanStopRunnable = Runnable {
                try {
                    // 检查是否正在清理
                    if (isCleaningUp) {
                        Log.d(TAG, "正在清理中，跳过延迟BLE扫描停止")
                        return@Runnable
                    }
                    stopBleScan()
                } catch (e: Exception) {
                    Log.e(TAG, "延迟停止BLE扫描失败: ${e.message}")
                    // 如果是FragmentManager相关错误，记录但不抛出异常
                    if (e.message?.contains("FragmentManager") == true) {
                        Log.w(TAG, "FragmentManager已销毁，延迟BLE扫描停止操作被忽略")
                    }
                }
            }
            mainHandler.postDelayed(bleScanStopRunnable!!, 15000)
            
        } catch (e: Exception) {
            Log.e(TAG, "BLE扫描失败: ${e.message}")
            callback?.onError("❌ BLE扫描失败: ${e.message}")
            callback?.onStatusChanged("💡 尝试使用传统蓝牙扫描...")
            startClassicScan()
        }
    }
    
    /**
     * 开始传统蓝牙扫描
     */
    private fun startClassicScan() {
        try {
            registerClassicScanReceiver()
            bluetoothAdapter?.startDiscovery()
            Log.d(TAG, "传统蓝牙扫描已开始")
            callback?.onStatusChanged("📡 传统蓝牙扫描进行中...")
            
            // 15秒后停止扫描
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                stopClassicScan()
            }, 15000)
            
        } catch (e: Exception) {
            Log.e(TAG, "传统蓝牙扫描失败: ${e.message}")
            callback?.onError("❌ 传统蓝牙扫描失败: ${e.message}")
            callback?.onStatusChanged("💡 请检查蓝牙设置或重启设备")
        }
    }
    
    /**
     * 停止扫描
     */
    fun stopScan() {
        try {
            stopBleScan()
            stopClassicScan()
            callback?.onStatusChanged("扫描已停止")
        } catch (e: Exception) {
            Log.e(TAG, "停止扫描失败: ${e.message}")
        }
    }
    
    /**
     * 停止BLE扫描
     */
    private fun stopBleScan() {
        // 如果正在清理，直接返回
        if (isCleaningUp) {
            Log.d(TAG, "正在清理中，跳过BLE扫描停止")
            return
        }
        
        try {
            // 取消延迟任务
            bleScanStopRunnable?.let { 
                mainHandler.removeCallbacks(it)
                bleScanStopRunnable = null
            }
            
            bluetoothLeScanner?.stopScan(bleScanCallback)
            Log.d(TAG, "BLE扫描已停止")
            
            // 扫描完成后立即触发回调
            callback?.onStatusChanged("🔍 BLE扫描完成")
            callback?.onStatusChanged("📊 扫描结果：找到 ${discoveredDevices.size} 个设备")
            
            if (discoveredDevices.isEmpty()) {
                callback?.onStatusChanged("⚠️ 未发现任何设备")
                callback?.onStatusChanged("💡 建议：")
                callback?.onStatusChanged("   • 检查目标设备是否开启蓝牙")
                callback?.onStatusChanged("   • 确保设备在可见范围内")
                callback?.onStatusChanged("   • 尝试重启蓝牙服务")
            } else {
                callback?.onStatusChanged("✅ 扫描成功，请选择要连接的设备")
            }
            
            callback?.onScanComplete(discoveredDevices.toList())
        } catch (e: Exception) {
            Log.e(TAG, "停止BLE扫描失败: ${e.message}")
            // 如果是FragmentManager相关错误，记录但不抛出异常
            if (e.message?.contains("FragmentManager") == true) {
                Log.w(TAG, "FragmentManager已销毁，BLE扫描停止操作被忽略")
            }
        }
    }
    
    /**
     * 停止传统蓝牙扫描
     */
    private fun stopClassicScan() {
        try {
            bluetoothAdapter?.cancelDiscovery()
            unregisterClassicScanReceiver()
            Log.d(TAG, "传统蓝牙扫描已停止")
        } catch (e: Exception) {
            Log.e(TAG, "停止传统蓝牙扫描失败: ${e.message}")
        }
    }
    
    /**
     * 连接设备
     */
    fun connectToDevice(device: BluetoothDevice) {
        if (isConnecting || isConnected) {
            callback?.onError("正在连接或已连接")
            return
        }
        
        try {
            isConnecting = true
            callback?.onStatusChanged("正在连接设备: ${device.name}")
            
            // 检查权限
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                callback?.onError("缺少蓝牙连接权限")
                isConnecting = false
                return
            }
            
            // 连接设备
            bluetoothGatt = device.connectGatt(context, false, gattCallback)
            
        } catch (e: Exception) {
            Log.e(TAG, "连接失败: ${e.message}")
            callback?.onError("连接失败: ${e.message}")
            isConnecting = false
        }
    }
    
    /**
     * 断开连接
     */
    fun disconnect() {
        try {
            bluetoothGatt?.disconnect()
            bluetoothGatt?.close()
            bluetoothGatt = null
            currentService = null
            currentCharacteristic = null
            isConnected = false
            isConnecting = false
            callback?.onStatusChanged("已断开连接")
        } catch (e: Exception) {
            Log.e(TAG, "断开连接失败: ${e.message}")
        }
    }
    
    /**
     * 发送指令到设备
     */
    fun sendCommand(command: ByteArray) {
        if (!isConnected) {
            callback?.onCommandSent(false, "设备未连接")
            return
        }
        
        if (currentCharacteristic == null) {
            callback?.onCommandSent(false, "特征未找到，无法发送指令")
            return
        }
        
        try {
            // 检查权限
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                callback?.onCommandSent(false, "缺少蓝牙连接权限")
                return
            }
            
            // 设置特征值
            currentCharacteristic!!.value = command
            
            // 发送数据
            val success = bluetoothGatt?.writeCharacteristic(currentCharacteristic!!) ?: false
            
            if (success) {
                totalPacketsSent++
                totalBytesSent += command.size
                Log.d(TAG, "指令发送成功: ${command.joinToString(", ") { "0x%02X".format(it) }}")
                callback?.onCommandSent(true, "指令发送成功")
                callback?.onStatusChanged("已发送指令: ${command.joinToString(", ") { "0x%02X".format(it) }}")
            } else {
                Log.e(TAG, "指令发送失败")
                callback?.onCommandSent(false, "指令发送失败")
            }
            
        } catch (e: Exception) {
            Log.e(TAG, "发送指令异常: ${e.message}")
            callback?.onCommandSent(false, "发送指令异常: ${e.message}")
        }
    }
    
    /**
     * 构建轻迅协议数据包
     * 格式: [功能码(2字节)] [数据长度(2字节)] [数据内容] [CRC16(2字节)]
     */
    private fun buildProtocolPacket(functionCode: Int, data: ByteArray = ByteArray(0)): ByteArray {
        val dataLength = data.size
        val packetSize = Protocol.PACKET_HEADER_SIZE + dataLength + Protocol.CRC_SIZE
        val packet = ByteArray(packetSize)
        
        var index = 0
        
        // 功能码 (小端格式)
        packet[index++] = (functionCode and 0xFF).toByte()
        packet[index++] = ((functionCode shr 8) and 0xFF).toByte()
        
        // 数据长度 (小端格式)
        packet[index++] = (dataLength and 0xFF).toByte()
        packet[index++] = ((dataLength shr 8) and 0xFF).toByte()
        
        // 数据内容
        if (data.isNotEmpty()) {
            System.arraycopy(data, 0, packet, index, dataLength)
            index += dataLength
        }
        
        // CRC16校验
        val crc = calculateCRC16(packet, 0, Protocol.PACKET_HEADER_SIZE + dataLength)
        packet[index++] = (crc and 0xFF).toByte()
        packet[index++] = ((crc shr 8) and 0xFF).toByte()
        
        return packet
    }
    
    /**
     * 解析轻迅协议数据包
     */
    private fun parseProtocolPacket(packet: ByteArray): Triple<Int, Int, ByteArray>? {
        if (packet.size < Protocol.MIN_PACKET_SIZE) {
            Log.e(TAG, "数据包长度不足: ${packet.size} < ${Protocol.MIN_PACKET_SIZE}")
            return null
        }
        
        try {
            // 功能码 (小端格式)
            val functionCode = (packet[1].toInt() and 0xFF shl 8) or (packet[0].toInt() and 0xFF)
            
            // 数据长度 (小端格式)
            val dataLength = (packet[3].toInt() and 0xFF shl 8) or (packet[2].toInt() and 0xFF)
            
            // 验证数据包长度
            val expectedLength = Protocol.PACKET_HEADER_SIZE + dataLength + Protocol.CRC_SIZE
            if (packet.size != expectedLength) {
                Log.e(TAG, "数据包长度不匹配: 实际=${packet.size}, 期望=${expectedLength}")
                return null
            }
            
            // 提取数据内容
            val data = if (dataLength > 0) {
                ByteArray(dataLength)
            } else {
                ByteArray(0)
            }
            
            if (dataLength > 0) {
                System.arraycopy(packet, Protocol.PACKET_HEADER_SIZE, data, 0, dataLength)
            }
            
            // 验证CRC16
            val calculatedCrc = calculateCRC16(packet, 0, Protocol.PACKET_HEADER_SIZE + dataLength)
            val receivedCrc = (packet[packet.size - 1].toInt() and 0xFF shl 8) or (packet[packet.size - 2].toInt() and 0xFF)
            
            if (calculatedCrc != receivedCrc) {
                Log.e(TAG, "CRC校验失败: 计算=${calculatedCrc}, 接收=${receivedCrc}")
                return null
            }
            
            return Triple(functionCode, dataLength, data)
            
        } catch (e: Exception) {
            Log.e(TAG, "解析数据包异常: ${e.message}")
            return null
        }
    }
    
    /**
     * 处理接收到的协议数据
     */
    private fun handleProtocolData(packet: ByteArray) {
        // 首先尝试解析为轻迅协议数据包
        val parsed = parseProtocolPacket(packet)
        if (parsed != null) {
            val (functionCode, dataLength, data) = parsed
            
            totalPacketsReceived++
            totalBytesReceived += packet.size
            
            Log.d(TAG, "收到协议数据: 功能码=0x${functionCode.toString(16).uppercase()}, 数据长度=$dataLength")
            
            // 根据功能码处理数据
            when (functionCode) {
                Protocol.FUNC_QUERY_DEVICE_INFO -> handleDeviceInfoResponse(data)
                Protocol.FUNC_QUERY_BATTERY -> handleBatteryResponse(data)
                Protocol.FUNC_START_COLLECTION -> handleCollectionResponse(data)
                Protocol.FUNC_DATA_STREAM -> handleDataStream(data)
                Protocol.FUNC_ALARM_DATA -> handleAlarmData(data)
                Protocol.FUNC_STATUS_REPORT -> handleStatusReport(data)
                else -> {
                    Log.w(TAG, "未知功能码: 0x${functionCode.toString(16).uppercase()}")
                    callback?.onProtocolDataReceived(functionCode, data)
                }
            }
        } else {
            // 如果协议解析失败，尝试其他解析方式
            Log.w(TAG, "轻迅协议解析失败，尝试其他解析方式")
            handleRawData(packet)
        }
    }
    
    /**
     * 处理原始数据（非标准协议格式）
     */
    private fun handleRawData(data: ByteArray) {
        try {
            Log.d(TAG, "处理原始数据: ${data.size} 字节")
            
            // 检查是否是数据流（功能码0x8000）
            if (data.size >= 2) {
                val functionCode = (data[1].toInt() and 0xFF shl 8) or (data[0].toInt() and 0xFF)
                
                if (functionCode == Protocol.FUNC_DATA_STREAM) {
                    Log.d(TAG, "检测到数据流功能码: 0x${functionCode.toString(16).uppercase()}")
                    
                    // 提取数据内容（跳过功能码）
                    val dataContent = if (data.size > 2) {
                        ByteArray(data.size - 2)
                    } else {
                        ByteArray(0)
                    }
                    
                    if (dataContent.isNotEmpty()) {
                        System.arraycopy(data, 2, dataContent, 0, dataContent.size)
                    }
                    
                    // 处理数据流
                    handleDataStream(dataContent)
                    return
                }
            }
            
            // 如果不是已知格式，直接传递给回调
            Log.d(TAG, "未知数据格式，直接传递给回调")
            callback?.onDataReceived(data)
            callback?.onProtocolDataReceived(0xFFFF, data) // 使用特殊功能码表示原始数据
            
        } catch (e: Exception) {
            Log.e(TAG, "处理原始数据异常: ${e.message}")
            // 异常情况下仍然传递给回调
            callback?.onDataReceived(data)
        }
    }
    
    /**
     * 处理设备信息响应
     */
    private fun handleDeviceInfoResponse(data: ByteArray) {
        try {
            if (data.size < 20) {
                Log.e(TAG, "设备信息数据长度不足: ${data.size}")
                return
            }
            
            var index = 0
            
            // 设备ID (8字节)
            val deviceId = String(data, index, 8).trim { it <= ' ' }
            index += 8
            
            // 固件版本 (4字节)
            val firmwareVersion = String(data, index, 4).trim { it <= ' ' }
            index += 4
            
            // 硬件版本 (4字节)
            val hardwareVersion = String(data, index, 4).trim { it <= ' ' }
            index += 4
            
            // 序列号 (4字节)
            val serialNumber = String(data, index, 4).trim { it <= ' ' }
            index += 4
            
            // 制造商和型号 (剩余字节)
            val remainingData = String(data, index, data.size - index).trim { it <= ' ' }
            val parts = remainingData.split("|")
            val manufacturer = if (parts.isNotEmpty()) parts[0] else ""
            val model = if (parts.size > 1) parts[1] else ""
            
            deviceInfo = DeviceInfo(
                deviceId = deviceId,
                firmwareVersion = firmwareVersion,
                hardwareVersion = hardwareVersion,
                serialNumber = serialNumber,
                manufacturer = manufacturer,
                model = model,
                capabilities = listOf("ECG", "BLE", "轻迅协议V${Protocol.VERSION}")
            )
            
            Log.d(TAG, "设备信息: $deviceInfo")
            callback?.onDeviceInfoReceived(deviceInfo!!)
            callback?.onStatusChanged("设备信息已接收: $manufacturer $model")
            
        } catch (e: Exception) {
            Log.e(TAG, "处理设备信息响应异常: ${e.message}")
        }
    }
    
    /**
     * 处理电量响应
     */
    private fun handleBatteryResponse(data: ByteArray) {
        try {
            if (data.isNotEmpty()) {
                val batteryLevel = data[0].toInt() and 0xFF
                Log.d(TAG, "电量: $batteryLevel%")
                callback?.onBatteryLevelReceived(batteryLevel)
                callback?.onStatusChanged("电量: $batteryLevel%")
            }
        } catch (e: Exception) {
            Log.e(TAG, "处理电量响应异常: ${e.message}")
        }
    }
    
    /**
     * 处理采集响应
     */
    private fun handleCollectionResponse(data: ByteArray) {
        try {
            if (data.isNotEmpty()) {
                val status = data[0].toInt() and 0xFF
                isCollecting = status == Protocol.COLLECTION_ON
                Log.d(TAG, "采集状态: ${if (isCollecting) "开启" else "关闭"}")
                callback?.onCollectionStatusChanged(isCollecting)
                callback?.onStatusChanged("采集状态: ${if (isCollecting) "开启" else "关闭"}")
            }
        } catch (e: Exception) {
            Log.e(TAG, "处理采集响应异常: ${e.message}")
        }
    }
    
    /**
     * 处理数据流
     */
    private fun handleDataStream(data: ByteArray) {
        try {
            Log.d(TAG, "收到数据流: ${data.size} 字节")
            callback?.onDataReceived(data)
            callback?.onProtocolDataReceived(Protocol.FUNC_DATA_STREAM, data)
        } catch (e: Exception) {
            Log.e(TAG, "处理数据流异常: ${e.message}")
        }
    }
    
    /**
     * 处理报警数据
     */
    private fun handleAlarmData(data: ByteArray) {
        try {
            Log.d(TAG, "收到报警数据: ${data.size} 字节")
            callback?.onProtocolDataReceived(Protocol.FUNC_ALARM_DATA, data)
            callback?.onStatusChanged("收到报警数据")
        } catch (e: Exception) {
            Log.e(TAG, "处理报警数据异常: ${e.message}")
        }
    }
    
    /**
     * 处理状态报告
     */
    private fun handleStatusReport(data: ByteArray) {
        try {
            Log.d(TAG, "收到状态报告: ${data.size} 字节")
            callback?.onProtocolDataReceived(Protocol.FUNC_STATUS_REPORT, data)
            callback?.onStatusChanged("收到状态报告")
        } catch (e: Exception) {
            Log.e(TAG, "处理状态报告异常: ${e.message}")
        }
    }
    
    /**
     * 发送字符串指令（自动转换为字节数组）
     */
    fun sendStringCommand(command: String) {
        val commandBytes = command.toByteArray()
        sendCommand(commandBytes)
    }
    
    /**
     * 发送十六进制指令
     */
    fun sendHexCommand(hexString: String) {
        try {
            val command = hexString.replace(" ", "").replace("0x", "").replace(",", "")
            val bytes = ByteArray(command.length / 2)
            for (i in bytes.indices) {
                val index = i * 2
                bytes[i] = command.substring(index, index + 2).toInt(16).toByte()
            }
            sendCommand(bytes)
        } catch (e: Exception) {
            Log.e(TAG, "十六进制指令格式错误: ${e.message}")
            callback?.onCommandSent(false, "十六进制指令格式错误: ${e.message}")
        }
    }
    
    /**
     * 开启采集
     * 功能码: 0x0001
     * 数据格式: [采集开关(1字节)] [时间戳(8字节)]
     */
    fun startCollection(timestamp: Long = 0L) {
        try {
            val data = ByteArray(9)
            var index = 0
            
            // 采集开关: 0x01 (开启)
            data[index++] = Protocol.COLLECTION_ON.toByte()
            
            // 时间戳: 8字节 (小端格式)
            for (i in 0..7) {
                data[index++] = ((timestamp shr (i * 8)) and 0xFF).toByte()
            }
            
            val packet = buildProtocolPacket(Protocol.FUNC_START_COLLECTION, data)
            Log.d(TAG, "发送开启采集指令: ${packet.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(packet)
            
        } catch (e: Exception) {
            Log.e(TAG, "构建开启采集指令失败: ${e.message}")
            callback?.onCommandSent(false, "构建开启采集指令失败: ${e.message}")
        }
    }
    
    /**
     * 停止采集
     * 功能码: 0x0001
     * 数据格式: [采集开关(1字节)] [时间戳(8字节)]
     */
    fun stopCollection(timestamp: Long = 0L) {
        try {
            val data = ByteArray(9)
            var index = 0
            
            // 采集开关: 0x00 (关闭)
            data[index++] = Protocol.COLLECTION_OFF.toByte()
            
            // 时间戳: 8字节 (小端格式)
            for (i in 0..7) {
                data[index++] = ((timestamp shr (i * 8)) and 0xFF).toByte()
            }
            
            val packet = buildProtocolPacket(Protocol.FUNC_START_COLLECTION, data)
            Log.d(TAG, "发送停止采集指令: ${packet.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(packet)
            
        } catch (e: Exception) {
            Log.e(TAG, "构建停止采集指令失败: ${e.message}")
            callback?.onCommandSent(false, "构建停止采集指令失败: ${e.message}")
        }
    }
    
    /**
     * 查询设备信息
     * 功能码: 0x0000
     */
    fun queryDeviceInfo() {
        try {
            val packet = buildProtocolPacket(Protocol.FUNC_QUERY_DEVICE_INFO)
            Log.d(TAG, "发送查询设备信息指令: ${packet.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(packet)
        } catch (e: Exception) {
            Log.e(TAG, "构建查询设备信息指令失败: ${e.message}")
            callback?.onCommandSent(false, "构建查询设备信息指令失败: ${e.message}")
        }
    }
    
    /**
     * 查询电量
     * 功能码: 0x0002
     */
    fun queryBattery() {
        try {
            val packet = buildProtocolPacket(Protocol.FUNC_QUERY_BATTERY)
            Log.d(TAG, "发送查询电量指令: ${packet.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(packet)
        } catch (e: Exception) {
            Log.e(TAG, "构建查询电量指令失败: ${e.message}")
            callback?.onCommandSent(false, "构建查询电量指令失败: ${e.message}")
        }
    }
    
    /**
     * 设置采样率
     * 功能码: 0x0003
     * 数据格式: [采样率(2字节)]
     */
    fun setSampleRate(sampleRate: Int) {
        try {
            val data = ByteArray(2)
            data[0] = (sampleRate and 0xFF).toByte()
            data[1] = ((sampleRate shr 8) and 0xFF).toByte()
            
            val packet = buildProtocolPacket(Protocol.FUNC_SET_SAMPLE_RATE, data)
            Log.d(TAG, "发送设置采样率指令: ${packet.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(packet)
            
            currentSampleRate = sampleRate
            
        } catch (e: Exception) {
            Log.e(TAG, "构建设置采样率指令失败: ${e.message}")
            callback?.onCommandSent(false, "构建设置采样率指令失败: ${e.message}")
        }
    }
    
    /**
     * 设置增益
     * 功能码: 0x0004
     * 数据格式: [增益(1字节)]
     */
    fun setGain(gain: Int) {
        try {
            val data = ByteArray(1)
            data[0] = gain.toByte()
            
            val packet = buildProtocolPacket(Protocol.FUNC_SET_GAIN, data)
            Log.d(TAG, "发送设置增益指令: ${packet.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(packet)
            
            currentGain = gain
            
        } catch (e: Exception) {
            Log.e(TAG, "构建设置增益指令失败: ${e.message}")
            callback?.onCommandSent(false, "构建设置增益指令失败: ${e.message}")
        }
    }
    
    /**
     * 设置导联
     * 功能码: 0x0006
     * 数据格式: [导联(1字节)]
     */
    fun setLead(lead: Int) {
        try {
            val data = ByteArray(1)
            data[0] = lead.toByte()
            
            val packet = buildProtocolPacket(Protocol.FUNC_SET_LEAD, data)
            Log.d(TAG, "发送设置导联指令: ${packet.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(packet)
            
            currentLead = lead
            
        } catch (e: Exception) {
            Log.e(TAG, "构建设置导联指令失败: ${e.message}")
            callback?.onCommandSent(false, "构建设置导联指令失败: ${e.message}")
        }
    }
    
    /**
     * 工频滤波开关
     * 功能码: 0x000A
     * 数据格式: [开关状态(1字节)]
     */
    fun togglePowerLineFilter(enable: Boolean) {
        try {
            val data = ByteArray(1)
            data[0] = if (enable) Protocol.POWER_LINE_FILTER_ON.toByte() else Protocol.POWER_LINE_FILTER_OFF.toByte()
            
            val packet = buildProtocolPacket(Protocol.FUNC_POWER_LINE_FILTER, data)
            Log.d(TAG, "发送工频滤波${if (enable) "开启" else "关闭"}指令: ${packet.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(packet)
            
            powerLineFilterEnabled = enable
            
        } catch (e: Exception) {
            Log.e(TAG, "构建工频滤波指令失败: ${e.message}")
            callback?.onCommandSent(false, "构建工频滤波指令失败: ${e.message}")
        }
    }
    
    /**
     * 查询状态
     * 功能码: 0x000B
     */
    fun queryStatus() {
        try {
            val packet = buildProtocolPacket(Protocol.FUNC_QUERY_STATUS)
            Log.d(TAG, "发送查询状态指令: ${packet.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(packet)
        } catch (e: Exception) {
            Log.e(TAG, "构建查询状态指令失败: ${e.message}")
            callback?.onCommandSent(false, "构建查询状态指令失败: ${e.message}")
        }
    }
    
    /**
     * 设备复位
     * 功能码: 0x000C
     */
    fun resetDevice() {
        try {
            val packet = buildProtocolPacket(Protocol.FUNC_RESET_DEVICE)
            Log.d(TAG, "发送设备复位指令: ${packet.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(packet)
        } catch (e: Exception) {
            Log.e(TAG, "构建设备复位指令失败: ${e.message}")
            callback?.onCommandSent(false, "构建设备复位指令失败: ${e.message}")
        }
    }
    
    /**
     * 获取协议统计信息
     */
    fun getProtocolStats(): Map<String, Any?> {
        return mapOf(
            "totalPacketsSent" to totalPacketsSent,
            "totalBytesSent" to totalBytesSent,
            "totalPacketsReceived" to totalPacketsReceived,
            "totalBytesReceived" to totalBytesReceived,
            "isCollecting" to isCollecting,
            "currentSampleRate" to currentSampleRate,
            "currentGain" to currentGain,
            "currentLead" to currentLead,
            "powerLineFilterEnabled" to powerLineFilterEnabled,
            "deviceInfo" to deviceInfo
        )
    }
    
    /**
     * 直接连接到指定MAC地址的设备
     */
    fun connectToMacAddress(macAddress: String) {
        if (isConnecting || isConnected) {
            callback?.onError("正在连接或已连接")
            return
        }
        
        try {
            // 检查权限
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                callback?.onError("缺少蓝牙连接权限")
                return
            }
            
            // 检查蓝牙适配器
            if (bluetoothAdapter == null) {
                callback?.onError("蓝牙适配器未初始化")
                return
            }
            
            
            // 尝试获取设备
            val device = bluetoothAdapter!!.getRemoteDevice(macAddress)
            if (device == null) {
                callback?.onError("无法获取设备: $macAddress")
                return
            }
            
            Log.d(TAG, "尝试直接连接到设备: $macAddress")
            callback?.onStatusChanged("正在连接设备: $macAddress")
            callback?.onStatusChanged("⏱️ 连接超时时间: 30秒")
            callback?.onStatusChanged("💡 请确保目标设备:")
            callback?.onStatusChanged("   • 蓝牙已开启")
            callback?.onStatusChanged("   • 设置为可发现模式")
            callback?.onStatusChanged("   • 在10米范围内")
            callback?.onStatusChanged("   • 未与其他设备连接")
            
            isConnecting = true
            
            // 连接设备 - 使用autoConnect=false以获得更快的连接
            bluetoothGatt = device.connectGatt(context, false, gattCallback, BluetoothDevice.TRANSPORT_LE)
            
            // 设置连接超时
            android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                if (isConnecting && !isConnected) {
                    Log.w(TAG, "连接超时，尝试断开并重新连接")
                    callback?.onStatusChanged("⏰ 连接超时，正在重试...")
                    
                    // 断开当前连接
                    bluetoothGatt?.disconnect()
                    bluetoothGatt?.close()
                    bluetoothGatt = null
                    
                    // 重置状态
                    isConnecting = false
                    
                    // 尝试使用传统蓝牙连接
                    callback?.onStatusChanged("🔄 尝试使用传统蓝牙连接...")
                    bluetoothGatt = device.connectGatt(context, false, gattCallback, BluetoothDevice.TRANSPORT_AUTO)
                    isConnecting = true
                    
                    // 再次设置超时
                    android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
                        if (isConnecting && !isConnected) {
                            Log.e(TAG, "连接最终失败")
                            callback?.onError("❌ 连接失败: 设备无响应")
                            callback?.onStatusChanged("💡 建议:")
                            callback?.onStatusChanged("   • 检查目标设备蓝牙设置")
                            callback?.onStatusChanged("   • 尝试在系统蓝牙设置中手动配对")
                            callback?.onStatusChanged("   • 重启两台设备的蓝牙")
                            isConnecting = false
                        }
                    }, 15000) // 15秒超时
                }
            }, 30000) // 30秒超时
            
        } catch (e: Exception) {
            Log.e(TAG, "直接连接失败: ${e.message}")
            callback?.onError("直接连接失败: ${e.message}")
            isConnecting = false
        }
    }
    
    
    /**
     * 计算CRC16-CCITT-FALSE校验
     */
    private fun calculateCRC16(data: ByteArray, offset: Int, length: Int): Int {
        var crc = 0xFFFF
        
        for (i in offset until offset + length) {
            crc = crc xor (data[i].toInt() and 0xFF)
            for (j in 0..7) {
                if ((crc and 0x0001) != 0) {
                    crc = crc shr 1
                    crc = crc xor 0x8408
                } else {
                    crc = crc shr 1
                }
            }
        }
        
        return crc
    }
    
    /**
     * GATT回调
     */
    private val gattCallback = object : BluetoothGattCallback() {
        override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
            when (newState) {
                BluetoothProfile.STATE_CONNECTED -> {
                    Log.d(TAG, "设备已连接，状态: $status")
                    isConnected = true
                    isConnecting = false
                    callback?.onConnected(gatt.device)
                    callback?.onStatusChanged("✅ 设备已连接: ${gatt.device.name ?: gatt.device.address}")
                    
                    // 发现服务
                    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                        gatt.discoverServices()
                    }
                }
                BluetoothProfile.STATE_DISCONNECTED -> {
                    Log.d(TAG, "设备已断开，状态: $status")
                    isConnected = false
                    isConnecting = false
                    callback?.onDisconnected()
                    
                    when (status) {
                        0 -> {
                            callback?.onStatusChanged("❌ 设备已断开连接")
                            callback?.onStatusChanged("💡 可能原因：设备超出范围、蓝牙关闭、连接超时等")
                        }
                        8 -> {
                            callback?.onStatusChanged("❌ 连接超时")
                            callback?.onStatusChanged("💡 设备可能不可见或距离过远")
                        }
                        19 -> {
                            callback?.onStatusChanged("❌ 连接被拒绝")
                            callback?.onStatusChanged("💡 设备可能正在与其他设备连接")
                        }
                        22 -> {
                            callback?.onStatusChanged("❌ 连接失败")
                            callback?.onStatusChanged("💡 设备可能不支持此连接方式")
                        }
                        else -> {
                            callback?.onStatusChanged("❌ 连接失败，状态码: $status")
                            callback?.onStatusChanged("💡 请检查设备状态和设置")
                        }
                    }
                    callback?.onStatusChanged("🔄 如需重新连接，请点击'连接蓝牙'按钮")
                }
            }
        }
        
        override fun onServicesDiscovered(gatt: BluetoothGatt, status: Int) {
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.d(TAG, "服务发现成功")
                callback?.onStatusChanged("🔍 服务发现成功")
                
                // 打印所有可用服务
                val services = gatt.services
                Log.d(TAG, "设备提供的服务数量: ${services.size}")
                callback?.onStatusChanged("📋 发现 ${services.size} 个服务")
                
                for (service in services) {
                    Log.d(TAG, "发现服务: ${service.uuid}")
                    callback?.onStatusChanged("发现服务: ${service.uuid}")
                    
                    // 打印服务的所有特征
                    val characteristics = service.characteristics
                    Log.d(TAG, "服务 ${service.uuid} 的特征数量: ${characteristics.size}")
                    
                    for (characteristic in characteristics) {
                        Log.d(TAG, "发现特征: ${characteristic.uuid}")
                        callback?.onStatusChanged("发现特征: ${characteristic.uuid}")
                    }
                }
                
                // 尝试查找匹配的服务和特征
                var foundService: BluetoothGattService? = null
                var foundCharacteristic: BluetoothGattCharacteristic? = null
                var foundNotifyCharacteristic: BluetoothGattCharacteristic? = null
                
                // 首先尝试预设的UUID列表
                for (serviceUuid in SERVICE_UUIDS) {
                    val service = gatt.getService(serviceUuid)
                    if (service != null) {
                        Log.d(TAG, "找到匹配的服务: $serviceUuid")
                        foundService = service
                        
                        // 查找TX特征（用于发送数据）
                        for (characteristicUuid in CHARACTERISTIC_UUIDS) {
                            val characteristic = service.getCharacteristic(characteristicUuid)
                            if (characteristic != null) {
                                Log.d(TAG, "找到TX特征: $characteristicUuid")
                                foundCharacteristic = characteristic
                                break
                            }
                        }
                        
                        // 查找RX特征（用于接收数据）
                        for (notifyUuid in NOTIFY_CHARACTERISTIC_UUIDS) {
                            val notifyCharacteristic = service.getCharacteristic(notifyUuid)
                            if (notifyCharacteristic != null) {
                                Log.d(TAG, "找到RX特征: $notifyUuid")
                                foundNotifyCharacteristic = notifyCharacteristic
                                break
                            }
                        }
                        break
                    }
                }
                
                // 如果预设UUID没有找到，尝试智能检测
                if (foundService == null || foundCharacteristic == null || foundNotifyCharacteristic == null) {
                    Log.d(TAG, "预设UUID未找到匹配，尝试智能检测")
                    
                    // 查找所有非标准蓝牙服务的UUID
                    for (service in services) {
                        val serviceUuid = service.uuid.toString()
                        
                        // 跳过标准蓝牙服务（如2a00, 2a01等）
                        if (!serviceUuid.contains("00002a") && !serviceUuid.contains("000018")) {
                            Log.d(TAG, "发现自定义服务: $serviceUuid")
                            
                            // 查找该服务下的所有特征
                            for (characteristic in service.characteristics) {
                                val characteristicUuid = characteristic.uuid.toString()
                                
                                // 跳过标准特征
                                if (!characteristicUuid.contains("00002a")) {
                                    Log.d(TAG, "发现自定义特征: $characteristicUuid")
                                    
                                    // 检查特征是否支持写入（TX特征）
                                    if (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE != 0 ||
                                        characteristic.properties and BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE != 0) {
                                        
                                        Log.d(TAG, "找到支持写入的特征(TX): $characteristicUuid")
                                        if (foundService == null) foundService = service
                                        if (foundCharacteristic == null) foundCharacteristic = characteristic
                                    }
                                    
                                    // 检查特征是否支持通知（RX特征）
                                    if (characteristic.properties and BluetoothGattCharacteristic.PROPERTY_NOTIFY != 0 ||
                                        characteristic.properties and BluetoothGattCharacteristic.PROPERTY_INDICATE != 0) {
                                        
                                        Log.d(TAG, "找到支持通知的特征(RX): $characteristicUuid")
                                        if (foundService == null) foundService = service
                                        if (foundNotifyCharacteristic == null) foundNotifyCharacteristic = characteristic
                                    }
                                }
                            }
                            if (foundService != null && foundCharacteristic != null && foundNotifyCharacteristic != null) break
                        }
                    }
                }
                
                if (foundService != null && foundCharacteristic != null && foundNotifyCharacteristic != null) {
                    // 保存当前服务特征，用于发送和接收数据
                    currentService = foundService
                    currentCharacteristic = foundCharacteristic
                    currentNotifyCharacteristic = foundNotifyCharacteristic
                    
                    // 启用通知
                    if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                        Log.d(TAG, "=== 启用特征通知 ===")
                        Log.d(TAG, "服务UUID: ${foundService.uuid}")
                        Log.d(TAG, "TX特征UUID: ${foundCharacteristic.uuid}")
                        Log.d(TAG, "RX特征UUID: ${foundNotifyCharacteristic.uuid}")
                        Log.d(TAG, "TX特征属性: ${foundCharacteristic.properties}")
                        Log.d(TAG, "RX特征属性: ${foundNotifyCharacteristic.properties}")
                        
                        // 启用RX特征的通知
                        val success = gatt.setCharacteristicNotification(foundNotifyCharacteristic, true)
                        Log.d(TAG, "启用RX特征通知结果: $success")
                        
                        // 写入Descriptor来激活通知
                        val descriptor = foundNotifyCharacteristic.getDescriptor(
                            UUID.fromString("00002902-0000-1000-8000-00805f9b34fb") // Client Characteristic Configuration Descriptor
                        )
                        if (descriptor != null) {
                            descriptor.value = android.bluetooth.BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE
                            val writeSuccess = gatt.writeDescriptor(descriptor)
                            Log.d(TAG, "写入Descriptor结果: $writeSuccess")
                        } else {
                            Log.w(TAG, "未找到Client Characteristic Configuration Descriptor")
                        }
                        
                        callback?.onStatusChanged("📡 数据通道已建立，可以发送指令开始接收数据")
                        callback?.onStatusChanged("💡 提示: 长按'发送指令'按钮可以发送测试数据")
                    } else {
                        Log.e(TAG, "缺少BLUETOOTH_CONNECT权限")
                        callback?.onError("缺少BLUETOOTH_CONNECT权限")
                    }
                } else {
                    Log.e(TAG, "未找到匹配的服务或特征")
                    callback?.onError("未找到匹配的服务或特征，请检查设备协议")
                    
                    // 提供所有可用服务的UUID供参考
                    val availableServices = services.joinToString(", ") { it.uuid.toString() }
                    Log.d(TAG, "可用服务UUID: $availableServices")
                    callback?.onStatusChanged("可用服务: $availableServices")
                }
            } else {
                Log.e(TAG, "服务发现失败，状态: $status")
                callback?.onError("服务发现失败，状态: $status")
            }
        }
        
                override fun onDescriptorWrite(gatt: android.bluetooth.BluetoothGatt, descriptor: android.bluetooth.BluetoothGattDescriptor, status: Int) {
            if (status == android.bluetooth.BluetoothGatt.GATT_SUCCESS) {
                Log.d(TAG, "Descriptor写入成功: ${descriptor.uuid}")
                callback?.onStatusChanged("✅ Notify通道已激活，可以接收设备数据")
            } else {
                Log.e(TAG, "Descriptor写入失败，状态: $status")
                callback?.onError("Notify通道激活失败，状态: $status")
            }
        }
        
        override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
            val data = characteristic.value
            Log.d(TAG, "=== 蓝牙特征值变化 ===")
            Log.d(TAG, "特征UUID: ${characteristic.uuid}")
            Log.d(TAG, "当前RX特征UUID: ${currentNotifyCharacteristic?.uuid}")
            Log.d(TAG, "接收到数据: ${data.size} 字节")
            
            if (data.isNotEmpty()) {
                Log.d(TAG, "数据前10字节: ${data.take(10).joinToString(", ") { "0x%02X".format(it) }}")
                
                // 分析244字节数据包结构
                if (data.size == 244) {
                    Log.d(TAG, "=== 244字节数据包结构分析 ===")
                    Log.d(TAG, "前4字节: ${data.take(4).joinToString(", ") { "0x%02X".format(it) }}")
                    Log.d(TAG, "后4字节: ${data.takeLast(4).joinToString(", ") { "0x%02X".format(it) }}")
                    
                    // 尝试解析为轻迅协议
                    val functionCode = (data[1].toInt() and 0xFF shl 8) or (data[0].toInt() and 0xFF)
                    val dataLength = (data[3].toInt() and 0xFF shl 8) or (data[2].toInt() and 0xFF)
                    
                    Log.d(TAG, "解析功能码: 0x${functionCode.toString(16).uppercase()}")
                    Log.d(TAG, "解析数据长度: $dataLength")
                    
                                         if (functionCode == Protocol.FUNC_DATA_STREAM && dataLength == 238) {
                         Log.d(TAG, "✅ 确认是轻迅协议数据流包")
                         Log.d(TAG, "协议包结构: 功能码(2) + 数据长度(2) + 数据内容(238) + CRC16(2) = 244字节")
                         
                         // 提取238字节的设备数据内容（跳过功能码和数据长度，不包含CRC16）
                         val deviceData = ByteArray(238)
                         System.arraycopy(data, 4, deviceData, 0, 238)
                         
                         Log.d(TAG, "提取设备数据: ${deviceData.size} 字节")
                         Log.d(TAG, "设备数据前10字节: ${deviceData.take(10).joinToString(", ") { "0x%02X".format(it) }}")
                         
                         // 238字节设备数据直接传递给回调，不进行轻迅协议解析
                         Log.d(TAG, "✅ 设备数据直接传递给C++解析器")
                         callback?.onDataReceived(deviceData)
                         callback?.onProtocolDataReceived(Protocol.FUNC_DATA_STREAM, deviceData)
                    } else {
                        Log.d(TAG, "⚠️ 不是标准轻迅协议格式，尝试其他解析方式")
                        handleRawData(data)
                    }
                } else {
                    Log.d(TAG, "数据包大小: ${data.size} 字节，不是244字节")
                    handleRawData(data)
                }
            }
            
            // 检查是否是RX特征
            if (characteristic.uuid == currentNotifyCharacteristic?.uuid) {
                Log.d(TAG, "✅ 收到RX特征数据")
            } else {
                Log.d(TAG, "⚠️ 收到非RX特征数据，UUID不匹配")
                Log.d(TAG, "收到特征UUID: ${characteristic.uuid}")
                Log.d(TAG, "期望RX特征UUID: ${currentNotifyCharacteristic?.uuid}")
                callback?.onDataReceived(data)
            }
        }
    }
    
    /**
     * BLE扫描回调
     */
    private val bleScanCallback = object : ScanCallback() {
        override fun onScanResult(callbackType: Int, result: ScanResult) {
            super.onScanResult(callbackType, result)
            
            val device = result.device
            val deviceName = device.name ?: "未知设备"
            val deviceAddress = device.address
            val rssi = result.rssi
            
            Log.d(TAG, "发现BLE设备: $deviceName ($deviceAddress) RSSI: $rssi")
            
            // 显示详细的设备信息
            callback?.onStatusChanged("📱 发现BLE设备: $deviceName")
            callback?.onStatusChanged("   📍 地址: $deviceAddress")
            callback?.onStatusChanged("   📶 信号强度: $rssi dBm")
            
            // 检查是否是目标设备
            if (deviceAddress.equals("A4:C3:37:86:9F:73", ignoreCase = true) || 
                deviceAddress.equals("A4-C3-37-86-9F-73", ignoreCase = true)) {
                callback?.onStatusChanged("🎯 找到目标设备！")
                callback?.onStatusChanged("💡 建议：长按'连接蓝牙'按钮直接连接")
            }
            
            // 添加所有发现的设备（不进行过滤）
            addDiscoveredDevice(device)
            callback?.onDeviceFound(device)
        }
        
        override fun onScanFailed(errorCode: Int) {
            super.onScanFailed(errorCode)
            Log.e(TAG, "BLE扫描失败，错误码: $errorCode")
            
            val errorMessage = when (errorCode) {
                SCAN_FAILED_ALREADY_STARTED -> "扫描已在进行中"
                SCAN_FAILED_APPLICATION_REGISTRATION_FAILED -> "应用注册失败"
                SCAN_FAILED_FEATURE_UNSUPPORTED -> "设备不支持BLE"
                SCAN_FAILED_INTERNAL_ERROR -> "内部错误"
                SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES -> "硬件资源不足"
                else -> "未知错误: $errorCode"
            }
            
            callback?.onError("❌ BLE扫描失败: $errorMessage")
            callback?.onStatusChanged("💡 尝试使用传统蓝牙扫描...")
            
            // 扫描失败时完成扫描
            callback?.onStatusChanged("扫描完成，找到 ${discoveredDevices.size} 个设备")
            callback?.onScanComplete(discoveredDevices.toList())
        }
    }
    
    /**
     * 传统蓝牙扫描回调
     */
    private val classicScanReceiver = object : android.content.BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: android.content.Intent?) {
            when (intent?.action) {
                BluetoothDevice.ACTION_FOUND -> {
                    val device = intent.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
                    device?.let {
                        Log.d(TAG, "发现传统蓝牙设备: ${it.name ?: "未知"} (${it.address})")
                        
                        // 添加所有发现的设备（不进行过滤）
                        addDiscoveredDevice(it)
                        callback?.onDeviceFound(it)
                    }
                }
                BluetoothAdapter.ACTION_DISCOVERY_STARTED -> {
                    Log.d(TAG, "传统蓝牙扫描开始")
                }
                BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
                    Log.d(TAG, "传统蓝牙扫描完成")
                    callback?.onStatusChanged("扫描完成，找到 ${discoveredDevices.size} 个设备")
                    callback?.onScanComplete(discoveredDevices.toList())
                }
            }
        }
    }
    
    /**
     * 注册传统蓝牙扫描广播接收器
     */
    private fun registerClassicScanReceiver() {
        try {
            if (!isClassicScanReceiverRegistered) {
                val filter = android.content.IntentFilter().apply {
                    addAction(BluetoothDevice.ACTION_FOUND)
                    addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
                    addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
                }
                context.registerReceiver(classicScanReceiver, filter)
                isClassicScanReceiverRegistered = true
                Log.d(TAG, "传统蓝牙扫描广播接收器已注册")
            } else {
                Log.d(TAG, "传统蓝牙扫描广播接收器已注册，跳过重复注册")
            }
        } catch (e: Exception) {
            Log.e(TAG, "注册广播接收器失败: ${e.message}")
            isClassicScanReceiverRegistered = false
        }
    }
    
    /**
     * 注销传统蓝牙扫描广播接收器
     */
    private fun unregisterClassicScanReceiver() {
        try {
            // 检查接收器是否已注册
            if (isClassicScanReceiverRegistered) {
                context.unregisterReceiver(classicScanReceiver)
                isClassicScanReceiverRegistered = false
                Log.d(TAG, "传统蓝牙扫描广播接收器已注销")
            } else {
                Log.d(TAG, "传统蓝牙扫描广播接收器未注册，跳过注销")
            }
        } catch (e: Exception) {
            Log.e(TAG, "注销广播接收器失败: ${e.message}")
            isClassicScanReceiverRegistered = false
        }
    }
    
    /**
     * 添加发现的设备
     */
    fun addDiscoveredDevice(device: BluetoothDevice) {
        if (!discoveredDevices.contains(device)) {
            discoveredDevices.add(device)
            
            // 显示详细的设备信息
            val deviceName = device.name ?: "未知设备"
            val deviceAddress = device.address
            val deviceType = when (device.type) {
                BluetoothDevice.DEVICE_TYPE_CLASSIC -> "经典蓝牙"
                BluetoothDevice.DEVICE_TYPE_LE -> "低功耗蓝牙"
                BluetoothDevice.DEVICE_TYPE_DUAL -> "双模蓝牙"
                else -> "未知类型"
            }
            
            Log.d(TAG, "发现设备: $deviceName ($deviceAddress) - $deviceType")
            callback?.onStatusChanged("📱 发现设备: $deviceName")
            callback?.onStatusChanged("   📍 地址: $deviceAddress")
            callback?.onStatusChanged("   🔧 类型: $deviceType")
            
            // 检查是否是目标设备
            if (deviceAddress.equals("A4:C3:37:86:9F:73", ignoreCase = true) || 
                deviceAddress.equals("A4-C3-37-86-9F-73", ignoreCase = true)) {
                callback?.onStatusChanged("🎯 找到目标设备！")
                callback?.onStatusChanged("💡 建议：长按'连接蓝牙'按钮直接连接")
            }
            
            callback?.onDeviceFound(device)
        }
    }
    
    /**
     * 获取发现的设备列表
     */
    fun getDiscoveredDevices(): List<BluetoothDevice> {
        return discoveredDevices.toList()
    }
    
    /**
     * 获取连接状态
     */
    fun isConnected(): Boolean = isConnected
    
    /**
     * 获取连接中状态
     */
    fun isConnecting(): Boolean = isConnecting
    
    /**
     * 调试函数：检查当前连接状态和特征
     */
    fun debugConnectionStatus(): String {
        val status = StringBuilder()
        status.append("=== 连接状态调试信息 ===\n")
        status.append("连接状态: ${if (isConnected) "已连接" else "未连接"}\n")
        status.append("连接中状态: ${if (isConnecting) "连接中" else "未连接中"}\n")
        status.append("当前服务: ${currentService?.uuid ?: "未设置"}\n")
        status.append("当前TX特征: ${currentCharacteristic?.uuid ?: "未设置"}\n")
        status.append("当前RX特征: ${currentNotifyCharacteristic?.uuid ?: "未设置"}\n")
        status.append("RX特征属性: ${currentNotifyCharacteristic?.properties ?: "未设置"}\n")
        status.append("数据统计:\n")
        status.append("  发送包数: $totalPacketsSent\n")
        status.append("  发送字节: $totalBytesSent\n")
        status.append("  接收包数: $totalPacketsReceived\n")
        status.append("  接收字节: $totalBytesReceived\n")
        return status.toString()
    }
    
    /**
     * 清理资源
     */
    fun cleanup() {
        try {
            Log.d(TAG, "开始清理BluetoothManager资源")
            
            // 设置清理标志，防止后续操作
            isCleaningUp = true
            
            // 取消所有延迟任务
            bleScanStopRunnable?.let { 
                mainHandler.removeCallbacks(it)
                bleScanStopRunnable = null
                Log.d(TAG, "已取消BLE扫描延迟任务")
            }
            
            // 断开连接
            disconnect()
            
            // 停止扫描（现在会检查isCleaningUp标志）
            stopScan()
            
            // 注销广播接收器（如果已注册）
            if (isClassicScanReceiverRegistered) {
                unregisterClassicScanReceiver()
            }
            
            // 清理状态
            isClassicScanReceiverRegistered = false
            isConnected = false
            isConnecting = false
            
            Log.d(TAG, "BluetoothManager资源清理完成")
        } catch (e: Exception) {
            Log.e(TAG, "清理BluetoothManager资源时发生异常: ${e.message}")
        } finally {
            // 确保清理标志被设置
            isCleaningUp = true
        }
    }
    
    // ==================== PPTM设备命令方法 ====================
    
    /**
     * 发送PPTM开始采样命令
     * 使用PPTM协议编码器生成带CRC16校验的命令
     */
    fun sendPptmStartSampleCmd() {
        try {
            val command = pptmEncoder.createPptmStartSampleCmd()
            Log.d(TAG, "发送PPTM开始采样命令: ${command.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(command)
            callback?.onStatusChanged("📤 已发送PPTM开始采样命令")
        } catch (e: Exception) {
            Log.e(TAG, "发送PPTM开始采样命令失败: ${e.message}")
            callback?.onCommandSent(false, "发送PPTM开始采样命令失败: ${e.message}")
        }
    }
    
    /**
     * 发送PPTM停止采样命令
     * 使用PPTM协议编码器生成带CRC16校验的命令
     */
    fun sendPptmStopSampleCmd() {
        try {
            val command = pptmEncoder.createPptmStopSampleCmd()
            Log.d(TAG, "发送PPTM停止采样命令: ${command.joinToString(", ") { "0x%02X".format(it) }}")
            sendCommand(command)
            callback?.onStatusChanged("📤 已发送PPTM停止采样命令")
        } catch (e: Exception) {
            Log.e(TAG, "发送PPTM停止采样命令失败: ${e.message}")
            callback?.onCommandSent(false, "发送PPTM停止采样命令失败: ${e.message}")
        }
    }
    
    /**
     * 发送自定义PPTM命令
     * @param opcode 操作码
     * @param payload 负载数据
     */
    fun sendCustomPptmCmd(opcode: Short, payload: ByteArray) {
        try {
            val command = pptmEncoder.createCustomPptmCmd(opcode, payload)
            Log.d(TAG, "发送自定义PPTM命令: 操作码=0x%04X, 负载=${payload.joinToString(", ") { "0x%02X".format(it) }}".format(opcode))
            sendCommand(command)
            callback?.onStatusChanged("📤 已发送自定义PPTM命令: 操作码=0x%04X".format(opcode))
        } catch (e: Exception) {
            Log.e(TAG, "发送自定义PPTM命令失败: ${e.message}")
            callback?.onCommandSent(false, "发送自定义PPTM命令失败: ${e.message}")
        }
    }
    
    /**
     * 验证PPTM数据包CRC16校验
     * @param packet 完整数据包
     * @return 校验是否通过
     */
    fun verifyPptmPacket(packet: ByteArray): Boolean {
        return pptmEncoder.verifyCrc16(packet)
    }
    
    /**
     * 解析PPTM数据包
     * @param packet 完整数据包
     * @return 解析结果 (操作码, 负载数据) 或 null
     */
    fun parsePptmPacket(packet: ByteArray): Pair<Short, ByteArray>? {
        return pptmEncoder.parsePacket(packet)
    }
    
    /**
     * 获取PPTM编码器实例（用于调试）
     */
    fun getPptmEncoder(): PPTMCommandEncoder {
        return pptmEncoder
    }
}
