import Foundation import CoreBluetooth import Combine import os.log private let bleLogger = Logger(subsystem: "com.glassmouse.GlassRemote", category: "BLE") // MARK: - UUID(与眼镜端 ProxyBleServer.kt 完全一致) let GlassServiceUUID = CBUUID(string: "A9E0ABCD-0000-1000-8000-00805F9B34FB") let GlassWriteUUID = CBUUID(string: "A9E0ABCD-0001-1000-8000-00805F9B34FB") let GlassNotifyUUID = CBUUID(string: "A9E0ABCD-0002-1000-8000-00805F9B34FB") enum ConnectionState: String { case poweredOff = "蓝牙关闭" case idle = "未连接" case scanning = "扫描中…" case connecting = "连接中…" case ready = "已就绪" case failed = "连接失败" } /// 眼镜 BLE 桥接管理器(CoreBluetooth 中心设备)。 /// 所有 CoreBluetooth 回调都跑在 .main 队列上,因此可直接更新 @Published。 final class GlassBLEManager: NSObject, ObservableObject { @Published var centralState: CBManagerState = .unknown @Published var connectionState: ConnectionState = .idle @Published var log: [String] = [] @Published var glassesIp: String = "" /// 眼镜端是否告知无障碍可用:默认 false,但 UI 不要据此假设。 /// 只有收到眼镜端推送的 clickReady 字段后才用 hasReceivedClickReadyStatus 判定是否显示警告。 @Published var clickReady: Bool = false @Published var hasReceivedClickReadyStatus: Bool = false @Published var lastAck: String = "" // 眼镜端回读的系统状态(音量/亮度/常亮/授权),供 ControlView 展示与状态同步 @Published var glassVolume: Int = -1 @Published var glassVolumeMax: Int = 0 @Published var glassBrightness: Int = -1 @Published var glassScreenKeepOn: Bool? = nil @Published var glassWriteSettings: Bool? = nil private var central: CBCentralManager? private var peripheral: CBPeripheral? private var writeChar: CBCharacteristic? private var notifyChar: CBCharacteristic? private var connectRetries = 0 private var discoverTimer: DispatchWorkItem? private let maxRetries = 3 private let cachedIdKey = "glassPeripheralId" private var triedGapConnect = false // 本次连接周期内,已连接直连只试一次 private var isRecovering = false // 句柄失效自愈中,防止重复触发重连 override init() { super.init() clearLogFile() central = CBCentralManager(delegate: self, queue: .main) } // MARK: - 文件日志(便于 Mac 端 devicectl copy 拉取诊断) private func writeLogToFile(_ line: String) { guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } let url = dir.appendingPathComponent("ble_log.txt") guard let data = (line + "\n").data(using: .utf8) else { return } if FileManager.default.fileExists(atPath: url.path) { guard let fh = try? FileHandle(forWritingTo: url) else { return } fh.seekToEndOfFile() fh.write(data) try? fh.closeFile() } else { try? data.write(to: url) } } func clearLogFile() { guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return } let url = dir.appendingPathComponent("ble_log.txt") try? "==== session \(Date()) ====\n".write(to: url, atomically: true, encoding: .utf8) } // MARK: - 日志 func appendLog(_ s: String) { let t = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .medium) let line = "[\(t)] \(s)" bleLogger.info("\(line, privacy: .public)") print("GlassRemoteBLE: \(line)") writeLogToFile(line) if Thread.isMainThread { _append(line) } else { DispatchQueue.main.async { [weak self] in self?._append(line) } } } private func _append(_ line: String) { log.append(line) if log.count > 200 { log.removeFirst() } } // MARK: - 连接(带重试 + 服务发现超时) func connect() { connectRetries = 0 triedGapConnect = false beginConnect() } private func beginConnect() { guard let central = central else { return } guard central.state == .poweredOn else { appendLog("蓝牙未开启,请先在系统设置中打开蓝牙") return } // 优先复用系统已配对设备:官方 App 已与眼镜建立 ACL 链路时, // 用缓存的 identifier 直接拿到 peripheral 并 connect,iOS 会复用底层链路—— // 不重新配对、不重新扫描,绕过「官方 App 占用后眼镜停广播我们的服务」导致的扫不到问题。 // 前提是眼镜支持多 GATT 连接(Android 通常支持)。 if let saved = UserDefaults.standard.string(forKey: cachedIdKey), let uuid = UUID(uuidString: saved), let p = central.retrievePeripherals(withIdentifiers: [uuid]).first { appendLog("复用已配对眼镜(缓存):\(p.name ?? "unknown"),复用底层链路直连") peripheral = p connectionState = .connecting central.connect(p, options: nil) return } // 再尝试「系统已连接的所有 peripheral」(用 GAP 服务 0x1800 过滤,所有 BLE 设备都有)。 // 不依赖广播我们的服务:眼镜被官方 App 占用时虽停广播,但只要它已连到系统、 // 且 GATT server 上仍有我们的服务,这里就能拿到它并复用底层 ACL 链路直连。 if !triedGapConnect { triedGapConnect = true let allConn = central.retrieveConnectedPeripherals(withServices: [CBUUID(string: "1800")]) if let p = allConn.first { appendLog("眼镜已连系统(或正被其他 App 占用),尝试复用底层链路直连:\(p.name ?? "unknown")") peripheral = p connectionState = .connecting central.connect(p, options: nil) return } } appendLog("开始扫描眼镜 BLE(全局扫描,按名字匹配 INMO AIR3)") connectionState = .scanning // 不带 service UUID 过滤:眼镜端 BLE 服务在某些 Android doze/低功耗下可能停止广播 service UUID, // 但设备本身仍会广播名字。靠 didDiscover 里名字匹配兜底 central.scanForPeripherals(withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey: false]) DispatchQueue.main.asyncAfter(deadline: .now() + 15) { [weak self] in guard let self = self else { return } if self.connectionState == .scanning { self.central?.stopScan() if self.connectRetries < self.maxRetries { self.connectRetries += 1 self.appendLog("扫描超时,重试(\(self.connectRetries)/\(self.maxRetries))") self.beginConnect() } else { self.appendLog("多次扫描未找到眼镜:确认眼镜端 GlassMouse 已启动、蓝牙已开启并授权、且屏幕常亮") self.connectionState = .idle } } } } func disconnect() { discoverTimer?.cancel() if let p = peripheral, let c = central { c.cancelPeripheralConnection(p) } writeChar = nil notifyChar = nil connectionState = .idle } // MARK: - 发送命令(JSON,与 WebSocket 完全一致) func send(_ dict: [String: Any], withResponse: Bool = false) { // 除了句柄存在与状态位,还要校验底层链路的真实连接态: // app 在后台时链路可能已断而回调未及更新,仅凭 connectionState 会写出 invalidHandle。 guard let p = peripheral, let ch = writeChar, p.state == .connected else { appendLog("未连接,丢弃命令:\(dict["type"] ?? "")") // 曾就绪过却校验失败 = 链路被后台静默断开,主动重建而不是干等回调 if connectionState != .idle { recoverInvalidHandle() } return } guard connectionState == .ready else { appendLog("链路未就绪,丢弃命令:\(dict["type"] ?? "")") if connectionState != .idle { recoverInvalidHandle() } return } guard let data = try? JSONSerialization.data(withJSONObject: dict) else { return } let type: CBCharacteristicWriteType = withResponse ? .withResponse : .withoutResponse p.writeValue(data, for: ch, type: type) } /// 投屏长文本分片发送:把整条 JSON 按字节切片,眼镜端 ProxyBleServer 重组后交 handleCommand。 /// 普通短命令直接走 send() 即可;本方法用于 content 可能超 BLE MTU 的场景。 func sendFragmented(_ dict: [String: Any]) { guard let p = peripheral, let ch = writeChar, p.state == .connected else { appendLog("未连接,丢弃分片命令") if connectionState != .idle { recoverInvalidHandle() } return } guard connectionState == .ready else { appendLog("链路未就绪,丢弃分片命令") return } let contentStr = (dict["content"] as? String) ?? "" appendLog("发送 BLE 写 cmd=\(dict["type"] ?? ""), action=\(dict["action"] ?? ""), len=\(contentStr.count)字") guard let fullData = try? JSONSerialization.data(withJSONObject: dict), let fullStr = String(data: fullData, encoding: .utf8) else { appendLog("命令序列化失败,丢弃") return } let bytes = Data(fullStr.utf8) let chunkSize = 350 // 留足 MTU 余量(frag 头约 50 字节 + JSON 转义) let total = max(1, (bytes.count + chunkSize - 1) / chunkSize) // BLE 写 characteristic 是否支持 withResponse:优先用 withResponse 走可靠通道 // 短命令(≤chunkSize)单片就够;分片也逐片 .withResponse let writeType: CBCharacteristicWriteType = ch.properties.contains(.write) ? .withResponse : .withoutResponse appendLog("写类型:\(writeType == .withResponse ? "withResponse(可靠)" : "withoutResponse(快速)"),属性位=\(ch.properties.rawValue)") for i in 0.. 1 { Thread.sleep(forTimeInterval: 0.05) } } appendLog("已分片发送投屏命令(\(total) 片)") } // 便捷指令 func move(dx: Int, dy: Int) { send(["type": "mouse", "action": "move", "dx": dx, "dy": dy]) } func click() { send(["type": "mouse", "action": "click"], withResponse: true) } func scroll(dy: Int) { send(["type": "mouse", "action": "scroll", "dy": dy]) } func key(_ action: String) { send(["type": "key", "action": action], withResponse: true) } func screenOn() { key("screen_on") } func screenOff() { key("screen_off") } // 音量 / 亮度:走眼镜端 sys 命令(由眼镜系统侧执行) func volumeUp() { send(["type": "sys", "action": "volume", "delta": 1], withResponse: true) } func volumeDown() { send(["type": "sys", "action": "volume", "delta": -1], withResponse: true) } func brightnessUp() { send(["type": "sys", "action": "brightness", "delta": 1], withResponse: true) } func brightnessDown() { send(["type": "sys", "action": "brightness", "delta": -1], withResponse: true) } /// 打开眼镜「修改系统设置」授权页(首次调亮度需要,授予后永久有效) func grantWriteSettings() { send(["type": "sys", "action": "grant_write_settings"], withResponse: true) } /** * 真实硬件 touch 手势:通过 BLE 发到眼镜端走 GestureDescription 通道 * - swipe(x1,y1,x2,y2,duration): 滑动(单击 x1==x2,y1==y2) * - longpress(x,y,duration): 长按 * 效果等同 INMO 官方硬件 touch,能真正滑动进度条 */ func swipeGesture(x1: Int, y1: Int, x2: Int, y2: Int, durationMs: Int = 300) { send([ "type": "gesture", "action": "swipe", "x1": x1, "y1": y1, "x2": x2, "y2": y2, "duration": durationMs ], withResponse: true) } func longPressGesture(x: Int, y: Int, durationMs: Int = 800) { send([ "type": "gesture", "action": "longpress", "x1": x, "y1": x, "x2": x, "y2": y, "duration": durationMs ], withResponse: true) } func camera() { send(["type": "camera", "action": "capture"], withResponse: true) } func setCursor(_ visible: Bool) { send(["type": "cursor", "visible": visible], withResponse: true) } func queryIp() { send(["type": "sys", "action": "ip"], withResponse: true) } func queryStatus() { send(["type": "sys", "action": "status"], withResponse: true) } // MARK: - 解析眼镜回传(NOTIFY) private func handleNotify(_ data: Data) { guard let str = String(data: data, encoding: .utf8) else { return } lastAck = str appendLog("← \(str)") guard let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { return } if let action = obj["action"] as? String, action == "ip", let ip = obj["ip"] as? String { glassesIp = ip } if let clickReady = obj["clickReady"] as? Bool { let wasUnknown = !hasReceivedClickReadyStatus self.clickReady = clickReady self.hasReceivedClickReadyStatus = true if wasUnknown { appendLog("收到眼镜端无障碍状态: \(clickReady ? "已开启" : "未开启")") } } // 眼镜端系统状态回读(sys status 的返回) if (obj["action"] as? String) == "status" { if let v = obj["volume"] as? Int { glassVolume = v } if let m = obj["volumeMax"] as? Int { glassVolumeMax = m } if let b = obj["brightness"] as? Int { glassBrightness = b } if let k = obj["screenKeepOn"] as? Bool { glassScreenKeepOn = k } if let w = obj["writeSettings"] as? Bool { glassWriteSettings = w } appendLog("眼镜状态:音量 \(glassVolume)/\(glassVolumeMax) · 亮度 \(glassBrightness) · 常亮 \(glassScreenKeepOn == true ? "开" : "关") · 亮度授权 \(glassWriteSettings == true ? "有" : "无")") } // 亮度被拒:眼镜端未授予「修改系统设置」权限 if (obj["action"] as? String) == "brightness", (obj["result"] as? String) == "no_permission" { glassWriteSettings = false appendLog("⚠️ 亮度调节被拒:眼镜端未授予「修改系统设置」权限") } } } // MARK: - CBCentralManagerDelegate extension GlassBLEManager: CBCentralManagerDelegate { func centralManagerDidUpdateState(_ central: CBCentralManager) { centralState = central.state if central.state == .poweredOn { appendLog("蓝牙已开启") if connectionState == .idle { connect() } } else { appendLog("蓝牙状态异常:\(central.state.rawValue)") if central.state == .poweredOff { connectionState = .poweredOff } } } func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) { let name = peripheral.name ?? "(no name)" let svcUUIDs = (advertisementData[CBAdvertisementDataServiceUUIDsKey] as? [CBUUID]) ?? [] appendLog("发现:\(name) rssi=\(RSSI) svcUUIDs=\(svcUUIDs.map { $0.uuidString }.joined(separator: ","))") // 全局扫描兜底:服务过滤没找到时也会触发,发现 INMO AIR3 就连(用户眼镜唯一) // 名字匹配优先,避免误连别人/同款眼镜 guard name.uppercased().contains("INMO") || name.uppercased().contains("AIR3") else { appendLog("非目标设备,跳过:\(name)") return } central.stopScan() self.peripheral = peripheral connectionState = .connecting central.connect(peripheral, options: nil) } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { appendLog("✅ 已连接 ACL,准备发现服务…") // 关键:无条件作废旧特征句柄并回到 .connecting。 // BLE 链路在后台断开重连后,旧的 CBCharacteristic 在 iOS 侧已失效,沿用旧引用 // 写入会返回 CBError.invalidHandle(1);而旧逻辑在重连时「保持 .ready」,会让下方 // 6s 超时保护(判断 connectionState != .ready)永不触发 → UI 卡在假「已就绪」, // 表现为「显示已连接、但所有按键/投屏都写不进去」。 writeChar = nil notifyChar = nil connectionState = .connecting peripheral.delegate = self // 服务/特征发现超时保护:6s 内未就绪则断开重试(缩短避免长时间卡"连接中") discoverTimer?.cancel() discoverTimer = DispatchWorkItem { [weak self] in guard let self = self else { return } if self.connectionState != .ready { self.appendLog("⚠️ 发现服务/特征超时(6s),强制断开重连") self.central?.cancelPeripheralConnection(peripheral) self.writeChar = nil self.notifyChar = nil if self.connectRetries < self.maxRetries { self.connectRetries += 1 self.beginConnect() } else { self.appendLog("❌ 多次连接未就绪:眼镜端 BLE 广播异常或被占用。请检查眼镜 GLASSMouse App 是否在前台") self.connectionState = .idle } } } DispatchQueue.main.asyncAfter(deadline: .now() + 6, execute: discoverTimer!) // 先发一个 nil services 兜底(让眼镜把所有 service 列出来,便于诊断缺哪个) peripheral.discoverServices(nil) DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak peripheral] in peripheral?.discoverServices([GlassServiceUUID]) } } // iOS 13+ 才有:连接开始时调 func centralManager(_ central: CBCentralManager, willConnectTo peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { appendLog("⌛ willConnectTo: \(peripheral.name ?? "(no name)") rssi=\(RSSI) svcUUIDs=\(((advertisementData[CBAdvertisementDataServiceUUIDsKey] as? [CBUUID]) ?? []).map { $0.uuidString }.joined(separator: ","))") } func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { appendLog("❌ 连接失败:\(error?.localizedDescription ?? "未知") (code:\((error as NSError?)?.code ?? -1))") // 失败时必须显式把状态切走,避免无限卡 connecting writeChar = nil notifyChar = nil if connectRetries < maxRetries { connectRetries += 1 appendLog("重试(\(connectRetries)/\(maxRetries))") DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in self?.beginConnect() } } else { connectionState = .failed } } func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { discoverTimer?.cancel() appendLog("已断开:\(error?.localizedDescription ?? "正常")") connectionState = .idle writeChar = nil notifyChar = nil } } // MARK: - CBPeripheralDelegate extension GlassBLEManager: CBPeripheralDelegate { func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { if let e = error { appendLog("发现服务失败:\(e.localizedDescription)"); return } guard let services = peripheral.services else { return } let found = services.contains { $0.uuid == GlassServiceUUID } if !found { appendLog("⚠️ 眼镜已连但无我们的 GATT 服务(A9E0ABCD)。原因可能是:① 眼镜正被官方 App 占用、未广播我们的服务;② 眼镜上 GlassMouse App 未在前台运行(BLE 服务没启动)。建议:先在 iPhone 蓝牙设置断开官方 App 与眼镜的连接,确认眼镜上 GlassMouse 已启动,再点「连接」重试。") return } for svc in services where svc.uuid == GlassServiceUUID { peripheral.discoverCharacteristics([GlassWriteUUID, GlassNotifyUUID], for: svc) } } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { if let e = error { appendLog("发现特征失败:\(e.localizedDescription)"); return } for ch in service.characteristics ?? [] { if ch.uuid == GlassWriteUUID { writeChar = ch appendLog("✓ 写特征就绪") } else if ch.uuid == GlassNotifyUUID { notifyChar = ch appendLog("✓ 通知特征就绪") } } if let wc = writeChar, let nc = notifyChar { discoverTimer?.cancel() UserDefaults.standard.set(peripheral.identifier.uuidString, forKey: cachedIdKey) connectionState = .ready appendLog("✅ BLE 桥接就绪,可发送命令") // 先把旧订阅清掉(防止 BLE 自动重连后 notify 状态错乱 → write handle 失效) if nc.isNotifying { peripheral.setNotifyValue(false, for: nc) } peripheral.setNotifyValue(true, for: nc) appendLog("已订阅通知 (\(nc.isNotifying ? "确认" : "已申请"))") // 等 iOS 完成 notify subscribe 的 ATT 握手,再发起首条命令 DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in guard let self = self else { return } guard self.writeChar != nil, self.connectionState == .ready else { return } self.queryStatus() self.queryIp() } } } func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) { if let e = error { appendLog("订阅通知失败:\(e.localizedDescription)") } } func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { if error != nil { return } guard let d = characteristic.value else { return } handleNotify(d) } func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { guard let e = error else { appendLog("✓ 写入 ACK 收到") return } let ns = e as NSError appendLog("❌ 写入失败:\(e.localizedDescription) (code:\(ns.code))") // CBError.invalidHandle(1):句柄在链路重连后已失效,而 UI 可能仍停在「已就绪」。 // 主动重建链路自愈,避免「显示已连接却怎么按都没反应」。 if ns.domain == "CBErrorDomain", ns.code == CBError.invalidHandle.rawValue { recoverInvalidHandle() } } /// 前后台体检:app 从后台回到前台时调用。 /// BLE 链路可能在后台被系统静默断开,而 connectionState 仍停在 .ready, /// 表现为界面「已就绪」但所有按键被丢弃。此处按真实链路态纠正并自动重建。 func healthCheck() { guard connectionState == .ready else { return } if peripheral == nil || peripheral?.state != .connected || writeChar == nil { appendLog("🩺 前后台体检:链路已失效(UI 仍显示已就绪),自动重建…") recoverInvalidHandle() } else { appendLog("🩺 前后台体检:链路正常") } } /// 句柄失效自愈:作废旧句柄 → 断开 → 重新连接并重新发现服务 private func recoverInvalidHandle() { guard !isRecovering else { return } isRecovering = true appendLog("⚠️ 检测到 BLE 句柄失效,自动重建链路…") discoverTimer?.cancel() writeChar = nil notifyChar = nil connectionState = .connecting connectRetries = 0 if let p = peripheral, let c = central { c.cancelPeripheralConnection(p) } DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in guard let self = self else { return } self.isRecovering = false self.beginConnect() } } }