import Foundation import CoreBluetooth /// Structured provisioning error codes (matches Android's BeaconConfig error codes) enum ProvisioningError: String, LocalizedError { case bluetoothUnavailable = "BLUETOOTH_UNAVAILABLE" case connectionFailed = "CONNECTION_FAILED" case connectionTimeout = "CONNECTION_TIMEOUT" case serviceNotFound = "SERVICE_NOT_FOUND" case authFailed = "AUTH_FAILED" case writeFailed = "WRITE_FAILED" case verificationFailed = "VERIFICATION_FAILED" case disconnected = "DISCONNECTED" case noConfig = "NO_CONFIG" case timeout = "TIMEOUT" case unknown = "UNKNOWN" var errorDescription: String? { switch self { case .bluetoothUnavailable: return "Bluetooth not available" case .connectionFailed: return "Failed to connect to beacon" case .connectionTimeout: return "Connection timed out" case .serviceNotFound: return "Config service not found on device" case .authFailed: return "Authentication failed - all passwords rejected" case .writeFailed: return "Failed to write configuration" case .verificationFailed: return "Beacon not broadcasting expected values" case .disconnected: return "Unexpected disconnect" case .noConfig: return "No configuration provided" case .timeout: return "Operation timed out" case .unknown: return "Unknown error" } } } /// Result of a provisioning operation enum ProvisioningResult { case success(macAddress: String?) case failure(String) case failureWithCode(ProvisioningError, detail: String? = nil) } /// Configuration to write to a beacon struct BeaconConfig { let uuid: String // 32-char hex, no dashes let major: UInt16 let minor: UInt16 let measuredPower: Int8 // RSSI@1m (e.g., -59) - from server, NOT hardcoded let advInterval: UInt8 // Advertising interval raw value (e.g., 2 = 200ms) - from server let txPower: UInt8 // TX power level - from server let deviceName: String? // Service point name (max 20 ASCII chars for DX-Smart) init(uuid: String, major: UInt16, minor: UInt16, measuredPower: Int8, advInterval: UInt8, txPower: UInt8, deviceName: String? = nil) { self.uuid = uuid self.major = major self.minor = minor self.measuredPower = measuredPower self.advInterval = advInterval self.txPower = txPower self.deviceName = deviceName } } /// Result of reading a beacon's current configuration struct BeaconCheckResult { // Parsed DX-Smart iBeacon config var uuid: String? // iBeacon UUID (formatted with dashes) var major: UInt16? var minor: UInt16? var rssiAt1m: Int8? var advInterval: UInt16? // Raw value (multiply by 100 for ms) var txPower: UInt8? var deviceName: String? var battery: UInt8? var macAddress: String? var frameSlots: [UInt8]? // Discovery info var servicesFound: [String] = [] var characteristicsFound: [String] = [] var rawResponses: [String] = [] // Raw response hex for debugging var hasConfig: Bool { uuid != nil || major != nil || minor != nil || deviceName != nil } } /// Handles GATT connection and provisioning of beacons /// /// v2: Prevention over recovery. Instead of layers of retry/reconnect/resume logic, /// we ensure a solid connection and confirmed characteristics before ever writing. /// No extra frame overwriting — only configure Frame 1 (device info) and Frame 2 (iBeacon). class BeaconProvisioner: NSObject, ObservableObject { // MARK: - DX-Smart CP28 GATT Characteristics private static let DXSMART_SERVICE = CBUUID(string: "0000FFE0-0000-1000-8000-00805F9B34FB") private static let DXSMART_NOTIFY_CHAR = CBUUID(string: "0000FFE1-0000-1000-8000-00805F9B34FB") // Notifications (RX) private static let DXSMART_COMMAND_CHAR = CBUUID(string: "0000FFE2-0000-1000-8000-00805F9B34FB") // Commands (TX) private static let DXSMART_PASSWORD_CHAR = CBUUID(string: "0000FFE3-0000-1000-8000-00805F9B34FB") // Password auth // DX-Smart packet header private static let DXSMART_HEADER: [UInt8] = [0x4E, 0x4F] // DX-Smart connection passwords (tried in order until one works) private static let DXSMART_PASSWORDS = ["555555", "dx1234", "000000"] // DX-Smart command codes private enum DXCmd: UInt8 { case frameTable = 0x10 case frameSelectSlot0 = 0x11 // Frame 1 (device info) case frameSelectSlot1 = 0x12 // Frame 2 (iBeacon) case frameSelectSlot2 = 0x13 // Frame 3 case frameSelectSlot3 = 0x14 // Frame 4 case frameSelectSlot4 = 0x15 // Frame 5 case frameSelectSlot5 = 0x16 // Frame 6 case authCheck = 0x25 case deviceInfo = 0x30 case deviceName = 0x43 // Read device name case saveConfig = 0x60 case deviceInfoType = 0x61 // Set frame as device info (broadcasts name) case iBeaconType = 0x62 // Set frame as iBeacon case deviceNameWrite = 0x71 // Write device name (max 20 ASCII chars) case uuid = 0x74 case major = 0x75 case minor = 0x76 case rssiAt1m = 0x77 case advInterval = 0x78 case txPower = 0x79 case triggerOff = 0xA0 case frameDisable = 0xFF } @Published var state: ProvisioningState = .idle @Published var progress: String = "" enum ProvisioningState: Equatable { case idle case connecting case discoveringServices case authenticating case writing case verifying case success case failed(String) } private var centralManager: CBCentralManager! private var peripheral: CBPeripheral? private var beaconType: BeaconType = .unknown private var config: BeaconConfig? private var completion: ((ProvisioningResult) -> Void)? private var configService: CBService? private var characteristics: [CBUUID: CBCharacteristic] = [:] private var passwordIndex = 0 // DX-Smart provisioning state private var dxSmartAuthenticated = false private var dxSmartNotifySubscribed = false private var dxSmartCommandQueue: [Data] = [] private var dxSmartWriteIndex = 0 private var provisioningMacAddress: String? private var isTerminating = false // guards against re-entrant disconnect handling private var authDisconnectRetried = false // one-shot retry if disconnect during auth // Read config mode private enum OperationMode { case provisioning, readingConfig } private var operationMode: OperationMode = .provisioning private var readCompletion: ((BeaconCheckResult?, String?) -> Void)? private var readResult = BeaconCheckResult() private var readTimeout: DispatchWorkItem? // Read config exploration state private var allDiscoveredServices: [CBService] = [] private var servicesToExplore: [CBService] = [] // DX-Smart read query state private var dxReadQueries: [Data] = [] private var dxReadQueryIndex = 0 private var responseBuffer: [UInt8] = [] // Connection state private var connectionRetryCount = 0 private static let MAX_CONNECTION_RETRIES = 2 private var currentBeacon: DiscoveredBeacon? // Per-write timeout — if beacon doesn't ACK within this time, fail cleanly private var writeTimeoutTimer: DispatchWorkItem? private static let WRITE_TIMEOUT_SECONDS: Double = 5.0 // Response gating — wait for beacon's FFE1 notification after each write // before sending next command. Matches Android's responseChannel.receive(1000ms). // This is the KEY prevention mechanism: we never blast commands faster than // the beacon can process them. private var awaitingCommandResponse = false private var responseGateTimer: DispatchWorkItem? private static let RESPONSE_GATE_TIMEOUT: Double = 1.0 // Inter-command delay — gives the beacon MCU breathing room between commands. // Prevention > recovery: generous delays prevent supervision timeouts. private static let INTER_COMMAND_DELAY: Double = 0.5 private static let HEAVY_COMMAND_DELAY: Double = 1.0 // After frame select/type changes private static let PRE_AUTH_DELAY: Double = 2.0 // After discovery, before first auth write (0.8 was too short — beacons drop connection) private static let POST_AUTH_DELAY: Double = 1.5 // After auth, before first write // Readiness gate — don't start writing until we've confirmed all 3 chars private var requiredCharsConfirmed = false override init() { super.init() centralManager = CBCentralManager(delegate: self, queue: .main) } /// Re-retrieve peripheral from our own CBCentralManager (the one from scanner may not work) private func resolvePeripheral(_ beacon: DiscoveredBeacon) -> CBPeripheral { let retrieved = centralManager.retrievePeripherals(withIdentifiers: [beacon.peripheral.identifier]) return retrieved.first ?? beacon.peripheral } // MARK: - Provision /// Provision a beacon with the given configuration func provision(beacon: DiscoveredBeacon, config: BeaconConfig, completion: @escaping (ProvisioningResult) -> Void) { guard centralManager.state == .poweredOn else { completion(.failureWithCode(.bluetoothUnavailable)) return } let resolvedPeripheral = resolvePeripheral(beacon) self.peripheral = resolvedPeripheral self.beaconType = beacon.type self.config = config self.completion = completion self.operationMode = .provisioning self.passwordIndex = 0 self.characteristics.removeAll() self.dxSmartAuthenticated = false self.dxSmartNotifySubscribed = false self.dxSmartCommandQueue.removeAll() self.dxSmartWriteIndex = 0 self.provisioningMacAddress = nil self.isTerminating = false self.authDisconnectRetried = false self.awaitingCommandResponse = false self.requiredCharsConfirmed = false cancelResponseGateTimeout() self.connectionRetryCount = 0 self.currentBeacon = beacon state = .connecting progress = "Connecting to \(beacon.displayName)..." centralManager.connect(resolvedPeripheral, options: nil) // Global timeout: 45 seconds — if we haven't succeeded by then, something is fundamentally wrong. // No infinite retry loops. Fail fast, let the user retry. DispatchQueue.main.asyncAfter(deadline: .now() + 45) { [weak self] in guard let self = self else { return } if self.state != .success && self.state != .idle { if case .failed = self.state { return } self.fail("Operation timed out after 45s", code: .timeout) } } } /// Cancel current provisioning func cancel() { if let peripheral = peripheral { centralManager.cancelPeripheralConnection(peripheral) } cleanup() } // MARK: - Read Config /// Read the current configuration from a beacon func readConfig(beacon: DiscoveredBeacon, completion: @escaping (BeaconCheckResult?, String?) -> Void) { guard centralManager.state == .poweredOn else { completion(nil, "Bluetooth not available") return } let resolvedPeripheral = resolvePeripheral(beacon) self.peripheral = resolvedPeripheral self.beaconType = beacon.type self.operationMode = .readingConfig self.readCompletion = completion self.readResult = BeaconCheckResult() self.passwordIndex = 0 self.characteristics.removeAll() self.dxSmartAuthenticated = false self.dxSmartNotifySubscribed = false self.responseBuffer.removeAll() self.dxReadQueries.removeAll() self.dxReadQueryIndex = 0 self.allDiscoveredServices.removeAll() self.connectionRetryCount = 0 self.isTerminating = false self.currentBeacon = beacon self.servicesToExplore.removeAll() state = .connecting progress = "Connecting to \(beacon.displayName)..." centralManager.connect(resolvedPeripheral, options: nil) // 15-second timeout for read operations let timeout = DispatchWorkItem { [weak self] in guard let self = self, self.operationMode == .readingConfig else { return } DebugLog.shared.log("BLE: Read timeout reached") self.finishRead() } readTimeout = timeout DispatchQueue.main.asyncAfter(deadline: .now() + 15, execute: timeout) } // MARK: - Cleanup private func cleanup() { cancelWriteTimeout() cancelResponseGateTimeout() awaitingCommandResponse = false peripheral = nil config = nil completion = nil configService = nil characteristics.removeAll() dxSmartAuthenticated = false dxSmartNotifySubscribed = false dxSmartCommandQueue.removeAll() dxSmartWriteIndex = 0 provisioningMacAddress = nil isTerminating = false authDisconnectRetried = false requiredCharsConfirmed = false connectionRetryCount = 0 currentBeacon = nil state = .idle progress = "" } private func fail(_ message: String, code: ProvisioningError? = nil) { guard !isTerminating else { DebugLog.shared.log("BLE: fail() called but already terminating, ignoring") return } isTerminating = true DebugLog.shared.log("BLE: FAIL [\(code?.rawValue ?? "UNTYPED")] - \(message)") state = .failed(message) if let peripheral = peripheral, peripheral.state == .connected { centralManager.cancelPeripheralConnection(peripheral) } if let code = code { completion?(.failureWithCode(code, detail: message)) } else { completion?(.failure(message)) } cleanup() } private func succeed() { guard !isTerminating else { DebugLog.shared.log("BLE: succeed() called but already terminating, ignoring") return } isTerminating = true DebugLog.shared.log("BLE: SUCCESS! MAC=\(provisioningMacAddress ?? "unknown")") state = .success if let peripheral = peripheral, peripheral.state == .connected { centralManager.cancelPeripheralConnection(peripheral) } let mac = provisioningMacAddress completion?(.success(macAddress: mac)) cleanup() } // MARK: - DX-Smart CP28 Provisioning private func provisionDXSmart() { guard let service = configService else { fail("DX-Smart config service not found", code: .serviceNotFound) return } state = .discoveringServices progress = "Discovering characteristics..." peripheral?.discoverCharacteristics([ BeaconProvisioner.DXSMART_NOTIFY_CHAR, BeaconProvisioner.DXSMART_COMMAND_CHAR, BeaconProvisioner.DXSMART_PASSWORD_CHAR ], for: service) } /// Verify all 3 required characteristics are present before proceeding. /// This is PREVENTION: we confirm readiness upfront instead of discovering /// missing chars mid-write and trying to recover. private func verifyCharacteristicsAndProceed() { let hasFFE1 = characteristics[BeaconProvisioner.DXSMART_NOTIFY_CHAR] != nil let hasFFE2 = characteristics[BeaconProvisioner.DXSMART_COMMAND_CHAR] != nil let hasFFE3 = characteristics[BeaconProvisioner.DXSMART_PASSWORD_CHAR] != nil DebugLog.shared.log("BLE: Char check — FFE1=\(hasFFE1) FFE2=\(hasFFE2) FFE3=\(hasFFE3)") guard hasFFE2 && hasFFE3 else { fail("Required characteristics not found (FFE2=\(hasFFE2) FFE3=\(hasFFE3))", code: .serviceNotFound) return } requiredCharsConfirmed = true // Subscribe to FFE1 notifications first (if available), then authenticate if hasFFE1, let notifyChar = resolveCharacteristic(BeaconProvisioner.DXSMART_NOTIFY_CHAR) { DebugLog.shared.log("BLE: Subscribing to FFE1 notifications") peripheral?.setNotifyValue(true, for: notifyChar) } else { DebugLog.shared.log("BLE: FFE1 not found, proceeding to auth after stabilization delay") dxSmartNotifySubscribed = true // Same pre-auth delay even without FFE1 — beacon still needs time after discovery DebugLog.shared.log("BLE: Waiting \(BeaconProvisioner.PRE_AUTH_DELAY)s before auth...") DispatchQueue.main.asyncAfter(deadline: .now() + BeaconProvisioner.PRE_AUTH_DELAY) { [weak self] in self?.dxSmartAuthenticate() } } } /// Write password to FFE3 (tries multiple passwords in sequence) private func dxSmartAuthenticate() { guard let passwordChar = resolveCharacteristic(BeaconProvisioner.DXSMART_PASSWORD_CHAR) else { fail("FFE3 not found", code: .serviceNotFound) return } guard passwordIndex < BeaconProvisioner.DXSMART_PASSWORDS.count else { fail("Authentication failed - all passwords rejected", code: .authFailed) return } state = .authenticating let currentPassword = BeaconProvisioner.DXSMART_PASSWORDS[passwordIndex] progress = "Authenticating (\(passwordIndex + 1)/\(BeaconProvisioner.DXSMART_PASSWORDS.count))..." let passwordData = Data(currentPassword.utf8) DebugLog.shared.log("BLE: Auth attempt \(passwordIndex + 1)/\(BeaconProvisioner.DXSMART_PASSWORDS.count)") peripheral?.writeValue(passwordData, for: passwordChar, type: .withResponse) } /// Called when a password attempt fails — tries the next one private func dxSmartRetryNextPassword() { passwordIndex += 1 if passwordIndex < BeaconProvisioner.DXSMART_PASSWORDS.count { DebugLog.shared.log("BLE: Password rejected, trying next") DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in self?.dxSmartAuthenticate() } } else { fail("All \(BeaconProvisioner.DXSMART_PASSWORDS.count) passwords rejected", code: .authFailed) } } /// Build the command queue and start writing. /// /// v2 command sequence — only Frame 1 + Frame 2, no extra frame overwrites: /// 1. DeviceName 0x71 [name bytes] — service point name (max 20 ASCII) /// 2. Frame1_Select 0x11 — select frame 1 /// 3. Frame1_Type 0x61 — device info (broadcasts name) /// 4. Frame1_RSSI 0x77 [measuredPower] /// 5. Frame1_AdvInt 0x78 [advInterval] /// 6. Frame1_TxPow 0x79 [txPower] /// 7. Frame2_Select 0x12 — select frame 2 /// 8. Frame2_Type 0x62 — iBeacon /// 9. UUID 0x74 [16 bytes] /// 10. Major 0x75 [2 bytes BE] /// 11. Minor 0x76 [2 bytes BE] /// 12. RSSI@1m 0x77 [measuredPower] /// 13. AdvInterval 0x78 [advInterval] /// 14. TxPower 0x79 [txPower] /// 15. TriggerOff 0xA0 /// 16. SaveConfig 0x60 — persist to flash /// /// Frames 3-6 are left untouched (not disabled/overwritten). private func dxSmartWriteConfig() { guard let config = config else { fail("No config provided", code: .noConfig) return } state = .writing progress = "Writing configuration..." dxSmartCommandQueue.removeAll() dxSmartWriteIndex = 0 let measuredPowerByte = UInt8(bitPattern: config.measuredPower) // 1. DeviceName (0x71) if let name = config.deviceName, !name.isEmpty { let truncatedName = String(name.prefix(20)) let nameBytes = Array(truncatedName.utf8) dxSmartCommandQueue.append(buildDXPacket(cmd: .deviceNameWrite, data: nameBytes)) } // --- Frame 1: Device Info --- dxSmartCommandQueue.append(buildDXPacket(cmd: .frameSelectSlot0, data: [])) // 2. Select frame 1 dxSmartCommandQueue.append(buildDXPacket(cmd: .deviceInfoType, data: [])) // 3. Device info type dxSmartCommandQueue.append(buildDXPacket(cmd: .rssiAt1m, data: [measuredPowerByte])) // 4. RSSI dxSmartCommandQueue.append(buildDXPacket(cmd: .advInterval, data: [config.advInterval])) // 5. Adv interval dxSmartCommandQueue.append(buildDXPacket(cmd: .txPower, data: [config.txPower])) // 6. TX power // --- Frame 2: iBeacon --- dxSmartCommandQueue.append(buildDXPacket(cmd: .frameSelectSlot1, data: [])) // 7. Select frame 2 dxSmartCommandQueue.append(buildDXPacket(cmd: .iBeaconType, data: [])) // 8. iBeacon type // 9. UUID (16 bytes) if let uuidData = hexStringToData(config.uuid) { dxSmartCommandQueue.append(buildDXPacket(cmd: .uuid, data: Array(uuidData))) } // 10. Major (2 bytes BE) let majorHi = UInt8((config.major >> 8) & 0xFF) let majorLo = UInt8(config.major & 0xFF) dxSmartCommandQueue.append(buildDXPacket(cmd: .major, data: [majorHi, majorLo])) // 11. Minor (2 bytes BE) let minorHi = UInt8((config.minor >> 8) & 0xFF) let minorLo = UInt8(config.minor & 0xFF) dxSmartCommandQueue.append(buildDXPacket(cmd: .minor, data: [minorHi, minorLo])) // 12-14. RSSI, AdvInterval, TxPower for frame 2 dxSmartCommandQueue.append(buildDXPacket(cmd: .rssiAt1m, data: [measuredPowerByte])) dxSmartCommandQueue.append(buildDXPacket(cmd: .advInterval, data: [config.advInterval])) dxSmartCommandQueue.append(buildDXPacket(cmd: .txPower, data: [config.txPower])) // 15. TriggerOff dxSmartCommandQueue.append(buildDXPacket(cmd: .triggerOff, data: [])) // 16. SaveConfig — persist to flash dxSmartCommandQueue.append(buildDXPacket(cmd: .saveConfig, data: [])) DebugLog.shared.log("BLE: Command queue built: \(dxSmartCommandQueue.count) commands (no extra frame overwrites)") dxSmartSendNextCommand() } /// Resolve a characteristic from our cache, falling back to live service lookup. /// CoreBluetooth can invalidate cached CBCharacteristic references during connection /// parameter renegotiation (common at edge-of-range). When that happens, our dictionary /// entry goes stale. This method re-resolves from the peripheral's live service list. private func resolveCharacteristic(_ uuid: CBUUID) -> CBCharacteristic? { // Fast path: cached reference is still valid if let cached = characteristics[uuid] { return cached } // Fallback: walk the peripheral's live services to find it guard let services = peripheral?.services else { return nil } for service in services { guard let chars = service.characteristics else { continue } for char in chars where char.uuid == uuid { DebugLog.shared.log("BLE: Re-resolved \(uuid) from live service \(service.uuid)") characteristics[uuid] = char // Re-cache for next lookup return char } } return nil } /// Send the next command in the queue private func dxSmartSendNextCommand() { guard dxSmartWriteIndex < dxSmartCommandQueue.count else { cancelWriteTimeout() DebugLog.shared.log("BLE: All commands written successfully!") progress = "Configuration saved!" succeed() return } guard let commandChar = resolveCharacteristic(BeaconProvisioner.DXSMART_COMMAND_CHAR) else { // If FFE2 can't be resolved even from live services, connection is truly broken. fail("FFE2 characteristic lost during write (not recoverable from live services)", code: .writeFailed) return } let packet = dxSmartCommandQueue[dxSmartWriteIndex] let current = dxSmartWriteIndex + 1 let total = dxSmartCommandQueue.count progress = "Writing config (\(current)/\(total))..." DebugLog.shared.log("BLE: Write \(current)/\(total): \(packet.map { String(format: "%02X", $0) }.joined(separator: " "))") scheduleWriteTimeout() peripheral?.writeValue(packet, for: commandChar, type: .withResponse) } /// Per-write timeout — fail cleanly if beacon doesn't ACK private func scheduleWriteTimeout() { cancelWriteTimeout() let timer = DispatchWorkItem { [weak self] in guard let self = self, self.state == .writing else { return } let current = self.dxSmartWriteIndex + 1 let total = self.dxSmartCommandQueue.count let isSaveConfig = self.dxSmartWriteIndex >= total - 1 if isSaveConfig { // SaveConfig may not ACK — beacon reboots. That's success. DebugLog.shared.log("BLE: SaveConfig timeout (beacon rebooted) — success") self.succeed() } else { // Any other command timing out is a real problem DebugLog.shared.log("BLE: Write timeout at step \(current)/\(total)") self.fail("Write timeout at step \(current)/\(total)", code: .writeFailed) } } writeTimeoutTimer = timer DispatchQueue.main.asyncAfter(deadline: .now() + BeaconProvisioner.WRITE_TIMEOUT_SECONDS, execute: timer) } private func cancelWriteTimeout() { writeTimeoutTimer?.cancel() writeTimeoutTimer = nil } /// Calculate delay for the command we just wrote. /// Frame selection and type commands need extra time (MCU state change). private func delayForCommand(at index: Int) -> Double { guard index < dxSmartCommandQueue.count else { return BeaconProvisioner.INTER_COMMAND_DELAY } let packet = dxSmartCommandQueue[index] guard packet.count >= 3 else { return BeaconProvisioner.INTER_COMMAND_DELAY } let cmd = packet[2] switch DXCmd(rawValue: cmd) { case .frameSelectSlot0, .frameSelectSlot1, .deviceInfoType, .iBeaconType: return BeaconProvisioner.HEAVY_COMMAND_DELAY case .uuid: return BeaconProvisioner.HEAVY_COMMAND_DELAY // Large payload default: return BeaconProvisioner.INTER_COMMAND_DELAY } } // MARK: - Response Gating /// After a successful write, wait for FFE1 response then advance. private func advanceToNextCommand() { let justWritten = dxSmartWriteIndex dxSmartWriteIndex += 1 let delay = delayForCommand(at: justWritten) DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in self?.dxSmartSendNextCommand() } } /// Wait up to 1s for beacon FFE1 response. If none, advance anyway. private func scheduleResponseGateTimeout() { cancelResponseGateTimeout() let timer = DispatchWorkItem { [weak self] in guard let self = self, self.awaitingCommandResponse else { return } self.awaitingCommandResponse = false DebugLog.shared.log("BLE: No FFE1 response within 1s for cmd \(self.dxSmartWriteIndex + 1) — advancing") self.advanceToNextCommand() } responseGateTimer = timer DispatchQueue.main.asyncAfter(deadline: .now() + BeaconProvisioner.RESPONSE_GATE_TIMEOUT, execute: timer) } private func cancelResponseGateTimeout() { responseGateTimer?.cancel() responseGateTimer = nil } // MARK: - DX-Smart Packet Builder /// Build a DX-Smart CP28 packet: [4E][4F][CMD][LEN][DATA...][XOR_CHECKSUM] private func buildDXPacket(cmd: DXCmd, data: [UInt8]) -> Data { var packet: [UInt8] = [] packet.append(contentsOf: BeaconProvisioner.DXSMART_HEADER) // 4E 4F packet.append(cmd.rawValue) packet.append(UInt8(data.count)) packet.append(contentsOf: data) var checksum: UInt8 = cmd.rawValue ^ UInt8(data.count) for byte in data { checksum ^= byte } packet.append(checksum) return Data(packet) } // MARK: - Read Config: Service Exploration private func startReadExplore() { guard let services = peripheral?.services, !services.isEmpty else { readFail("No services found on device") return } allDiscoveredServices = services servicesToExplore = services state = .discoveringServices progress = "Exploring \(services.count) services..." DebugLog.shared.log("BLE: Read mode — found \(services.count) services") for s in services { readResult.servicesFound.append(s.uuid.uuidString) } exploreNextService() } private func exploreNextService() { guard !servicesToExplore.isEmpty else { DebugLog.shared.log("BLE: All services explored, starting DX-Smart read") startDXSmartRead() return } let service = servicesToExplore.removeFirst() DebugLog.shared.log("BLE: Discovering chars for service \(service.uuid)") progress = "Exploring \(service.uuid.uuidString.prefix(8))..." peripheral?.discoverCharacteristics(nil, for: service) } // MARK: - Read Config: DX-Smart Protocol private func startDXSmartRead() { guard characteristics[BeaconProvisioner.DXSMART_PASSWORD_CHAR] != nil, characteristics[BeaconProvisioner.DXSMART_COMMAND_CHAR] != nil else { DebugLog.shared.log("BLE: No FFE0 service — not a DX-Smart beacon") progress = "No DX-Smart service found" finishRead() return } if let notifyChar = characteristics[BeaconProvisioner.DXSMART_NOTIFY_CHAR] { DebugLog.shared.log("BLE: Read mode — subscribing to FFE1") progress = "Subscribing to notifications..." peripheral?.setNotifyValue(true, for: notifyChar) } else { DebugLog.shared.log("BLE: FFE1 not found, attempting auth without notifications") dxSmartReadAuth() } } private func dxSmartReadAuth() { guard let passwordChar = resolveCharacteristic(BeaconProvisioner.DXSMART_PASSWORD_CHAR) else { DebugLog.shared.log("BLE: No FFE3 for auth (even after live lookup), finishing") finishRead() return } guard passwordIndex < BeaconProvisioner.DXSMART_PASSWORDS.count else { DebugLog.shared.log("BLE: All passwords exhausted in read mode") finishRead() return } state = .authenticating let currentPassword = BeaconProvisioner.DXSMART_PASSWORDS[passwordIndex] progress = "Authenticating (\(passwordIndex + 1)/\(BeaconProvisioner.DXSMART_PASSWORDS.count))..." let passwordData = Data(currentPassword.utf8) DebugLog.shared.log("BLE: Read mode — auth attempt \(passwordIndex + 1)") peripheral?.writeValue(passwordData, for: passwordChar, type: .withResponse) } private func dxSmartReadQueryAfterAuth() { dxReadQueries.removeAll() dxReadQueryIndex = 0 responseBuffer.removeAll() dxReadQueries.append(buildDXPacket(cmd: .frameTable, data: [])) // Frame table dxReadQueries.append(buildDXPacket(cmd: .iBeaconType, data: [])) // iBeacon config dxReadQueries.append(buildDXPacket(cmd: .deviceInfo, data: [])) // Device info dxReadQueries.append(buildDXPacket(cmd: .deviceName, data: [])) // Device name DebugLog.shared.log("BLE: Sending \(dxReadQueries.count) read queries") state = .verifying progress = "Reading config..." dxSmartSendNextReadQuery() } private func dxSmartSendNextReadQuery() { guard dxReadQueryIndex < dxReadQueries.count else { DebugLog.shared.log("BLE: All read queries sent, waiting 2s for responses") progress = "Collecting responses..." DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { [weak self] in guard let self = self, self.operationMode == .readingConfig else { return } self.finishRead() } return } guard let commandChar = resolveCharacteristic(BeaconProvisioner.DXSMART_COMMAND_CHAR) else { DebugLog.shared.log("BLE: FFE2 not found (even after live lookup), finishing read") finishRead() return } let packet = dxReadQueries[dxReadQueryIndex] let current = dxReadQueryIndex + 1 let total = dxReadQueries.count progress = "Reading \(current)/\(total)..." DebugLog.shared.log("BLE: Read query \(current)/\(total): \(packet.map { String(format: "%02X", $0) }.joined(separator: " "))") peripheral?.writeValue(packet, for: commandChar, type: .withResponse) } // MARK: - Read Config: Response Parsing private func processFFE1Response(_ data: Data) { let hex = data.map { String(format: "%02X", $0) }.joined(separator: " ") DebugLog.shared.log("BLE: FFE1 raw: \(hex)") responseBuffer.append(contentsOf: data) while responseBuffer.count >= 5 { guard let headerIdx = findDXHeader() else { responseBuffer.removeAll() break } if headerIdx > 0 { responseBuffer.removeFirst(headerIdx) } guard responseBuffer.count >= 5 else { break } let cmd = responseBuffer[2] let len = Int(responseBuffer[3]) let frameLen = 4 + len + 1 guard responseBuffer.count >= frameLen else { break } let frame = Array(responseBuffer[0.. Int? { guard responseBuffer.count >= 2 else { return nil } for i in 0..<(responseBuffer.count - 1) { if responseBuffer[i] == 0x4E && responseBuffer[i + 1] == 0x4F { return i } } return nil } private func parseResponseCmd(cmd: UInt8, data: [UInt8]) { let dataHex = data.map { String(format: "%02X", $0) }.joined(separator: " ") DebugLog.shared.log("BLE: Response cmd=0x\(String(format: "%02X", cmd)) len=\(data.count) data=[\(dataHex)]") readResult.rawResponses.append("0x\(String(format: "%02X", cmd)): \(dataHex)") switch DXCmd(rawValue: cmd) { case .frameTable: readResult.frameSlots = data DebugLog.shared.log("BLE: Frame slots: \(data.map { String(format: "0x%02X", $0) })") case .iBeaconType: guard data.count >= 2 else { return } var offset = 1 if data.count >= offset + 16 { let uuidBytes = Array(data[offset..<(offset + 16)]) let uuidHex = uuidBytes.map { String(format: "%02X", $0) }.joined() readResult.uuid = formatUUID(uuidHex) offset += 16 } if data.count >= offset + 2 { readResult.major = UInt16(data[offset]) << 8 | UInt16(data[offset + 1]) offset += 2 } if data.count >= offset + 2 { readResult.minor = UInt16(data[offset]) << 8 | UInt16(data[offset + 1]) offset += 2 } if data.count >= offset + 1 { readResult.rssiAt1m = Int8(bitPattern: data[offset]) offset += 1 } if data.count >= offset + 1 { readResult.advInterval = UInt16(data[offset]) offset += 1 } if data.count >= offset + 1 { readResult.txPower = data[offset] offset += 1 } DebugLog.shared.log("BLE: iBeacon — UUID=\(readResult.uuid ?? "?") Major=\(readResult.major ?? 0) Minor=\(readResult.minor ?? 0)") case .deviceInfo: if data.count >= 1 { readResult.battery = data[0] } if data.count >= 7 { let macBytes = Array(data[1..<7]) readResult.macAddress = macBytes.map { String(format: "%02X", $0) }.joined(separator: ":") } DebugLog.shared.log("BLE: Device info — battery=\(readResult.battery ?? 0)% MAC=\(readResult.macAddress ?? "?")") case .deviceName: readResult.deviceName = String(bytes: data, encoding: .utf8)?.trimmingCharacters(in: .controlCharacters) DebugLog.shared.log("BLE: Device name = \(readResult.deviceName ?? "?")") case .authCheck: if data.count >= 1 { DebugLog.shared.log("BLE: Auth required: \(data[0] != 0x00)") } default: DebugLog.shared.log("BLE: Unhandled response cmd 0x\(String(format: "%02X", cmd))") } } // MARK: - Read Config: Finish private func finishRead() { readTimeout?.cancel() readTimeout = nil if let peripheral = peripheral { centralManager.cancelPeripheralConnection(peripheral) } let result = readResult state = .success progress = "" readCompletion?(result, nil) cleanupRead() } private func readFail(_ message: String) { DebugLog.shared.log("BLE: Read failed - \(message)") readTimeout?.cancel() readTimeout = nil if let peripheral = peripheral { centralManager.cancelPeripheralConnection(peripheral) } state = .failed(message) readCompletion?(nil, message) cleanupRead() } private func cleanupRead() { peripheral = nil readCompletion = nil readResult = BeaconCheckResult() readTimeout = nil dxReadQueries.removeAll() dxReadQueryIndex = 0 responseBuffer.removeAll() allDiscoveredServices.removeAll() servicesToExplore.removeAll() configService = nil characteristics.removeAll() connectionRetryCount = 0 currentBeacon = nil operationMode = .provisioning state = .idle progress = "" } // MARK: - Helpers private func hexStringToData(_ hex: String) -> Data? { let clean = hex.normalizedUUID guard clean.count == 32 else { return nil } var data = Data() var index = clean.startIndex while index < clean.endIndex { let nextIndex = clean.index(index, offsetBy: 2) let byteString = String(clean[index.. String { let clean = hex.uppercased() guard clean.count == 32 else { return hex } let c = Array(clean) return "\(String(c[0..<8]))-\(String(c[8..<12]))-\(String(c[12..<16]))-\(String(c[16..<20]))-\(String(c[20..<32]))" } } // MARK: - CBCentralManagerDelegate extension BeaconProvisioner: CBCentralManagerDelegate { func centralManagerDidUpdateState(_ central: CBCentralManager) { DebugLog.shared.log("BLE: Central state = \(central.state.rawValue)") } func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { DebugLog.shared.log("BLE: Connected to \(peripheral.name ?? "unknown")") peripheral.delegate = self let maxWriteLen = peripheral.maximumWriteValueLength(for: .withResponse) DebugLog.shared.log("BLE: Max write length: \(maxWriteLen) bytes") if maxWriteLen < 21 { DebugLog.shared.log("BLE: WARNING — max write \(maxWriteLen) < 21 bytes needed for UUID packet") } state = .discoveringServices progress = "Discovering services..." if operationMode == .readingConfig { peripheral.discoverServices(nil) } else { peripheral.discoverServices([BeaconProvisioner.DXSMART_SERVICE]) } } func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { let errorMsg = error?.localizedDescription ?? "unknown error" DebugLog.shared.log("BLE: Connection failed: \(errorMsg)") // Simple retry: up to 2 attempts with short delay if connectionRetryCount < BeaconProvisioner.MAX_CONNECTION_RETRIES { connectionRetryCount += 1 let delay = Double(connectionRetryCount) progress = "Connection failed, retrying (\(connectionRetryCount)/\(BeaconProvisioner.MAX_CONNECTION_RETRIES))..." DebugLog.shared.log("BLE: Retrying connection in \(delay)s") DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in guard let self = self, let beacon = self.currentBeacon else { return } guard self.state == .connecting else { return } let resolvedPeripheral = self.resolvePeripheral(beacon) self.peripheral = resolvedPeripheral self.centralManager.connect(resolvedPeripheral, options: nil) } } else { let msg = "Failed to connect after \(BeaconProvisioner.MAX_CONNECTION_RETRIES) attempts: \(errorMsg)" if operationMode == .readingConfig { readFail(msg) } else { fail(msg, code: .connectionFailed) } } } func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { DebugLog.shared.log("BLE: Disconnected | state=\(state) mode=\(operationMode) writeIdx=\(dxSmartWriteIndex) queueCount=\(dxSmartCommandQueue.count) error=\(error?.localizedDescription ?? "none")") // Expected cleanup disconnect if isTerminating { DebugLog.shared.log("BLE: Disconnect during termination, ignoring") return } if operationMode == .readingConfig { if state != .success && state != .idle { finishRead() } return } // Already terminal if state == .success || state == .idle { return } if case .failed = state { return } // SaveConfig was the last command — beacon rebooted. That's success. if state == .writing && dxSmartCommandQueue.count > 0 && dxSmartWriteIndex >= dxSmartCommandQueue.count - 1 { DebugLog.shared.log("BLE: Disconnect after SaveConfig — treating as success") succeed() return } // Cancel pending timers cancelWriteTimeout() cancelResponseGateTimeout() awaitingCommandResponse = false // If we disconnect during authentication and haven't retried yet, // reconnect once — the beacon may just need a fresh connection with more settling time. if state == .authenticating && !authDisconnectRetried { authDisconnectRetried = true DebugLog.shared.log("BLE: Disconnect during auth — retrying connection once") progress = "Reconnecting..." state = .connecting passwordIndex = 0 dxSmartNotifySubscribed = false requiredCharsConfirmed = false characteristics.removeAll() configService = nil // Brief pause before reconnecting DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in guard let self = self, let peripheral = self.peripheral else { return } self.centralManager.connect(peripheral, options: nil) } return } // Any other disconnect during active work = fail immediately. // Prevention philosophy: if the connection dropped, something is wrong. // Don't try to reconnect and resume — let the user retry cleanly. fail("Beacon disconnected during \(state). Move closer and try again.", code: .disconnected) } } // MARK: - CBPeripheralDelegate extension BeaconProvisioner: CBPeripheralDelegate { /// Handle service invalidation — CoreBluetooth calls this when the remote device's /// GATT database changes (e.g., connection parameter renegotiation at edge-of-range). /// Invalidated services have their characteristics wiped. We clear our cache and /// re-discover so resolveCharacteristic() can find them again. func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) { let uuids = invalidatedServices.map { $0.uuid.uuidString } DebugLog.shared.log("BLE: Services invalidated: \(uuids)") // Clear cached characteristics for invalidated services for service in invalidatedServices { if let chars = service.characteristics { for char in chars { characteristics.removeValue(forKey: char.uuid) } } } // If our config service was invalidated, re-discover it let invalidatedUUIDs = invalidatedServices.map { $0.uuid } if invalidatedUUIDs.contains(BeaconProvisioner.DXSMART_SERVICE) { DebugLog.shared.log("BLE: FFE0 service invalidated — re-discovering") configService = nil peripheral.discoverServices([BeaconProvisioner.DXSMART_SERVICE]) } } func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { if let error = error { if operationMode == .readingConfig { readFail("Service discovery failed: \(error.localizedDescription)") } else { fail("Service discovery failed: \(error.localizedDescription)", code: .serviceNotFound) } return } guard let services = peripheral.services else { if operationMode == .readingConfig { readFail("No services found") } else { fail("No services found", code: .serviceNotFound) } return } DebugLog.shared.log("BLE: Discovered \(services.count) services") if operationMode == .readingConfig { startReadExplore() return } // Provisioning: look for DX-Smart service for service in services { if service.uuid == BeaconProvisioner.DXSMART_SERVICE { configService = service provisionDXSmart() return } } fail("Config service not found on device", code: .serviceNotFound) } func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { if let error = error { if operationMode == .readingConfig { DebugLog.shared.log("BLE: Char discovery failed for \(service.uuid): \(error.localizedDescription)") exploreNextService() } else { fail("Characteristic discovery failed: \(error.localizedDescription)", code: .serviceNotFound) } return } guard let chars = service.characteristics else { if operationMode == .readingConfig { exploreNextService() } else { fail("No characteristics found", code: .serviceNotFound) } return } DebugLog.shared.log("BLE: Discovered \(chars.count) characteristics for \(service.uuid)") for char in chars { let props = char.properties let propStr = [ props.contains(.read) ? "R" : "", props.contains(.write) ? "W" : "", props.contains(.writeWithoutResponse) ? "Wn" : "", props.contains(.notify) ? "N" : "", props.contains(.indicate) ? "I" : "" ].filter { !$0.isEmpty }.joined(separator: ",") DebugLog.shared.log(" Char: \(char.uuid) [\(propStr)]") characteristics[char.uuid] = char if operationMode == .readingConfig { readResult.characteristicsFound.append("\(char.uuid.uuidString)[\(propStr)]") } } if operationMode == .readingConfig { exploreNextService() } else { // PREVENTION: verify all required chars exist before proceeding verifyCharacteristicsAndProceed() } } func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { cancelWriteTimeout() if let error = error { DebugLog.shared.log("BLE: Write failed for \(characteristic.uuid): \(error.localizedDescription)") // Password rejected if characteristic.uuid == BeaconProvisioner.DXSMART_PASSWORD_CHAR { if passwordIndex + 1 < BeaconProvisioner.DXSMART_PASSWORDS.count { dxSmartRetryNextPassword() } else if operationMode == .readingConfig { readFail("Authentication failed - all passwords rejected") } else { fail("All passwords rejected", code: .authFailed) } return } // Command write failed if characteristic.uuid == BeaconProvisioner.DXSMART_COMMAND_CHAR { if operationMode == .readingConfig { dxReadQueryIndex += 1 DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { [weak self] in self?.dxSmartSendNextReadQuery() } } else { let isSaveConfig = dxSmartWriteIndex >= dxSmartCommandQueue.count - 1 let isFrame1Command = dxSmartWriteIndex < 6 // Frame 1 commands are non-fatal if isSaveConfig { // SaveConfig write "error" = beacon rebooted mid-ACK. Success. DebugLog.shared.log("BLE: SaveConfig write error (beacon rebooted) — success") succeed() } else if isFrame1Command { // Frame 1 (device info) commands are optional — skip and continue DebugLog.shared.log("BLE: Non-fatal command failed at step \(dxSmartWriteIndex + 1), skipping") dxSmartWriteIndex += 1 DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in self?.dxSmartSendNextCommand() } } else { fail("Write failed at step \(dxSmartWriteIndex + 1)/\(dxSmartCommandQueue.count): \(error.localizedDescription)", code: .writeFailed) } } return } if operationMode == .readingConfig { return } fail("Write failed: \(error.localizedDescription)", code: .writeFailed) return } DebugLog.shared.log("BLE: Write OK for \(characteristic.uuid)") // Password auth succeeded if characteristic.uuid == BeaconProvisioner.DXSMART_PASSWORD_CHAR { DebugLog.shared.log("BLE: Authenticated!") dxSmartAuthenticated = true if operationMode == .readingConfig { dxSmartReadQueryAfterAuth() } else { // Give the beacon breathing room after auth before we start writing DebugLog.shared.log("BLE: Waiting \(BeaconProvisioner.POST_AUTH_DELAY)s before writing...") progress = "Authenticated, preparing to write..." DispatchQueue.main.asyncAfter(deadline: .now() + BeaconProvisioner.POST_AUTH_DELAY) { [weak self] in self?.dxSmartWriteConfig() } } return } // Command write succeeded — gate on FFE1 response if characteristic.uuid == BeaconProvisioner.DXSMART_COMMAND_CHAR { if operationMode == .readingConfig { dxReadQueryIndex += 1 DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { [weak self] in self?.dxSmartSendNextReadQuery() } } else { awaitingCommandResponse = true scheduleResponseGateTimeout() } return } } func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) { if let error = error { DebugLog.shared.log("BLE: Notification state failed for \(characteristic.uuid): \(error.localizedDescription)") } else { DebugLog.shared.log("BLE: Notifications \(characteristic.isNotifying ? "enabled" : "disabled") for \(characteristic.uuid)") } if characteristic.uuid == BeaconProvisioner.DXSMART_NOTIFY_CHAR { dxSmartNotifySubscribed = true if operationMode == .readingConfig { dxSmartReadAuth() } else { // Give the beacon a moment to stabilize after discovery + notification subscribe // before we hit it with a password write. Without this, DX-Smart beacons drop // the connection during auth (supervision timeout). DebugLog.shared.log("BLE: Waiting \(BeaconProvisioner.PRE_AUTH_DELAY)s before auth...") DispatchQueue.main.asyncAfter(deadline: .now() + BeaconProvisioner.PRE_AUTH_DELAY) { [weak self] in self?.dxSmartAuthenticate() } } } } func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { if let error = error { DebugLog.shared.log("BLE: Read error for \(characteristic.uuid): \(error.localizedDescription)") return } let data = characteristic.value ?? Data() if operationMode == .readingConfig { if characteristic.uuid == BeaconProvisioner.DXSMART_NOTIFY_CHAR { processFFE1Response(data) } else { let hex = data.map { String(format: "%02X", $0) }.joined(separator: " ") DebugLog.shared.log("BLE: Read \(characteristic.uuid): \(hex)") } } else { // Provisioning mode — FFE1 notification if characteristic.uuid == BeaconProvisioner.DXSMART_NOTIFY_CHAR { let hex = data.map { String(format: "%02X", $0) }.joined(separator: " ") DebugLog.shared.log("BLE: FFE1 notification: \(hex)") if awaitingCommandResponse { awaitingCommandResponse = false cancelResponseGateTimeout() // Check for rejection (4E 4F 00 = command rejected) let bytes = [UInt8](data) if bytes.count >= 3 && bytes[0] == 0x4E && bytes[1] == 0x4F && bytes[2] == 0x00 { let isFrame1 = dxSmartWriteIndex < 6 DebugLog.shared.log("BLE: Command \(dxSmartWriteIndex + 1) rejected\(isFrame1 ? " (non-fatal)" : "")") } advanceToNextCommand() } } } } }