|
|
|
@ -46,6 +46,8 @@ public class BleService: NSObject { |
|
|
|
private var isScanning = false |
|
|
|
private var scanTimer: Timer? |
|
|
|
|
|
|
|
// 用于存储配对设备UUID的UserDefaults键 |
|
|
|
private let pairedDeviceUUIDKey = "com.yunqiinnovation.ble_service.paired_device_uuid" |
|
|
|
// 新增:设备缓存和广播数据记录 |
|
|
|
private var discoveredDevices: [String: [String: Any]] = [:] // 以设备ID为key的设备信息缓存 |
|
|
|
private var deviceAdvertisementData: [String: [String: Any]] = [:] // 设备广播数据缓存 |
|
|
|
@ -164,6 +166,27 @@ public class BleService: NSObject { |
|
|
|
return centralManager! |
|
|
|
} |
|
|
|
|
|
|
|
func getPairedMacAddress() -> String? { |
|
|
|
let uuidString = UserDefaults.standard.string(forKey: pairedDeviceUUIDKey) |
|
|
|
if let uuidString = uuidString, !uuidString.isEmpty { |
|
|
|
os_log("获取已配对设备UUID: %{public}@", log: logger, type: .info, uuidString) |
|
|
|
return uuidString |
|
|
|
} |
|
|
|
os_log("未找到已配对设备UUID", log: logger, type: .info) |
|
|
|
return nil |
|
|
|
} |
|
|
|
/// 清除已保存的配对设备UUID |
|
|
|
private func clearPairedMacAddress() { |
|
|
|
UserDefaults.standard.removeObject(forKey: pairedDeviceUUIDKey) |
|
|
|
UserDefaults.standard.synchronize() |
|
|
|
os_log("已清除配对设备UUID", log: logger, type: .info) |
|
|
|
} |
|
|
|
// MARK: - 清除配对关系 |
|
|
|
func clearAssociations() { |
|
|
|
resetBluetoothState() |
|
|
|
// 清除保存的配对设备UUID |
|
|
|
clearPairedMacAddress() |
|
|
|
} |
|
|
|
/// 开始扫描BLE设备 |
|
|
|
public func startScan(timeout: TimeInterval = 30.0) -> Bool { |
|
|
|
if centralManager == nil { |
|
|
|
@ -208,20 +231,6 @@ public class BleService: NSObject { |
|
|
|
isScanning = false |
|
|
|
scanTimer?.invalidate() |
|
|
|
scanTimer = nil |
|
|
|
|
|
|
|
// let deviceCount = discoveredDevices.count |
|
|
|
// os_log("⏹️ 停止BLE扫描,共发现 %d 个设备", log: logger, type: .info, deviceCount) |
|
|
|
// |
|
|
|
// // 打印所有发现的设备摘要 |
|
|
|
// if deviceCount > 0 { |
|
|
|
// os_log("📋 扫描结果摘要:", log: logger, type: .info) |
|
|
|
// for (index, deviceInfo) in discoveredDevices.values.enumerated() { |
|
|
|
// if let name = deviceInfo["name"] as? String, |
|
|
|
// let rssi = deviceInfo["rssi"] as? Int { |
|
|
|
// os_log("📋 %d. %{public}@ (RSSI: %d)", log: logger, type: .info, index + 1, name, rssi) |
|
|
|
// } |
|
|
|
// } |
|
|
|
// } |
|
|
|
} |
|
|
|
} |
|
|
|
|
|
|
|
@ -417,6 +426,10 @@ public class BleService: NSObject { |
|
|
|
|
|
|
|
// MARK: - 回调通知方法 |
|
|
|
|
|
|
|
//清除蓝牙状态(仅用于测试或重置,不会清除系统授权) |
|
|
|
func resetBluetoothState() { |
|
|
|
|
|
|
|
} |
|
|
|
/// 通知所有回调扫描结果 |
|
|
|
private func notifyScanResult(devices: [[String: Any]]) { |
|
|
|
for callback in callbacks { |
|
|
|
|