fix: eliminate flickering by using single authoritative probe for connection state
This commit is contained in:
parent
a11f6bcc38
commit
c907a24b56
3 changed files with 93 additions and 198 deletions
BIN
BLTS-Tracker.dmg
BIN
BLTS-Tracker.dmg
Binary file not shown.
|
|
@ -107,9 +107,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
||||||
// Start active tracking
|
// Start active tracking
|
||||||
tracker.startTracking()
|
tracker.startTracking()
|
||||||
|
|
||||||
// Fast 0.5s timer in AppDelegate
|
// Regular safety UI sync timer in AppDelegate
|
||||||
let t = Timer.scheduledTimer(withTimeInterval: 0.5, repeats: true) { [weak self] _ in
|
let t = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [weak self] _ in
|
||||||
self?.tracker.updateDeviceList()
|
|
||||||
self?.updateStatusItem()
|
self?.updateStatusItem()
|
||||||
}
|
}
|
||||||
RunLoop.main.add(t, forMode: .common)
|
RunLoop.main.add(t, forMode: .common)
|
||||||
|
|
|
||||||
|
|
@ -19,9 +19,6 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
|
|
||||||
private var timerSource: DispatchSourceTimer?
|
private var timerSource: DispatchSourceTimer?
|
||||||
private var knownBatteries: [String: Int] = [:]
|
private var knownBatteries: [String: Int] = [:]
|
||||||
|
|
||||||
private typealias VoidFn = @convention(c) (AnyObject, Selector) -> Void
|
|
||||||
private typealias IntBatteryGetter = @convention(c) (AnyObject, Selector) -> Int
|
|
||||||
private typealias BoolGetter = @convention(c) (AnyObject, Selector) -> Bool
|
private typealias BoolGetter = @convention(c) (AnyObject, Selector) -> Bool
|
||||||
|
|
||||||
public static func checkBluetoothPower() -> Bool {
|
public static func checkBluetoothPower() -> Bool {
|
||||||
|
|
@ -29,33 +26,9 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
return controller.powerState == kBluetoothHCIPowerStateON
|
return controller.powerState == kBluetoothHCIPowerStateON
|
||||||
}
|
}
|
||||||
|
|
||||||
private func syncFromServer(device: IOBluetoothDevice) {
|
|
||||||
let selUpdate = Selector(("updateFromServer"))
|
|
||||||
if device.responds(to: selUpdate) {
|
|
||||||
let imp = device.method(for: selUpdate)
|
|
||||||
let fn = unsafeBitCast(imp, to: VoidFn.self)
|
|
||||||
fn(device, selUpdate)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Force CoreBluetooth coordinator to purge cached peers and query bluetoothd
|
|
||||||
if let cls = NSClassFromString("IOBluetoothCoreBluetoothCoordinator") as? NSObject.Type,
|
|
||||||
let coord = cls.perform(Selector(("sharedInstance")))?.takeUnretainedValue() as? NSObject,
|
|
||||||
let mgr = coord.perform(Selector(("classicManager")))?.takeUnretainedValue() as? NSObject {
|
|
||||||
let selOrphan = Selector(("orphanClassicPeers"))
|
|
||||||
if mgr.responds(to: selOrphan) {
|
|
||||||
_ = mgr.perform(selOrphan)
|
|
||||||
}
|
|
||||||
let selReq = Selector(("sendLocalDeviceStateRequest"))
|
|
||||||
if mgr.responds(to: selReq) {
|
|
||||||
_ = mgr.perform(selReq)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public init() {
|
public init() {
|
||||||
self.isBluetoothPoweredOn = BluetoothTracker.checkBluetoothPower()
|
self.isBluetoothPoweredOn = BluetoothTracker.checkBluetoothPower()
|
||||||
setupBluetoothListeners()
|
setupBluetoothListeners()
|
||||||
setupAudioListeners()
|
|
||||||
startTracking()
|
startTracking()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -68,12 +41,16 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
updateDeviceList()
|
updateDeviceList()
|
||||||
pollSubprocessProbe()
|
pollSubprocessProbe()
|
||||||
|
|
||||||
// Strict 500ms DispatchSourceTimer for instant real-time reactivity
|
// Strict 1.0s timer for probe monitoring (with zero-flicker authoritative updates)
|
||||||
let timer = DispatchSource.makeTimerSource(flags: .strict, queue: DispatchQueue.main)
|
let timer = DispatchSource.makeTimerSource(flags: .strict, queue: DispatchQueue.main)
|
||||||
timer.schedule(deadline: .now() + 0.5, repeating: 0.5, leeway: .milliseconds(50))
|
timer.schedule(deadline: .now() + 1.0, repeating: 1.0, leeway: .milliseconds(50))
|
||||||
timer.setEventHandler { [weak self] in
|
timer.setEventHandler { [weak self] in
|
||||||
self?.updateDeviceList()
|
guard let self = self else { return }
|
||||||
self?.pollSubprocessProbe()
|
if !BluetoothTracker.checkBluetoothPower() {
|
||||||
|
self.applyPowerOffState()
|
||||||
|
} else {
|
||||||
|
self.pollSubprocessProbe()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
timer.resume()
|
timer.resume()
|
||||||
self.timerSource = timer
|
self.timerSource = timer
|
||||||
|
|
@ -86,33 +63,40 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
|
|
||||||
private var isProbeRunning = false
|
private var isProbeRunning = false
|
||||||
|
|
||||||
public func pollSubprocessProbe() {
|
private func resolveProbeBinary() -> (String, [String])? {
|
||||||
guard !isProbeRunning else { return }
|
// 1. Same directory as current executable
|
||||||
|
|
||||||
// Instant check: if Bluetooth is off, no need to run probe
|
|
||||||
if !BluetoothTracker.checkBluetoothPower() {
|
|
||||||
if isBluetoothPoweredOn || isConnected || currentBatteryPercent != nil {
|
|
||||||
applyPowerOffState()
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
var probeBin: String? = nil
|
|
||||||
var probeArgs: [String] = []
|
|
||||||
|
|
||||||
if let exeDir = Bundle.main.executableURL?.deletingLastPathComponent().path {
|
if let exeDir = Bundle.main.executableURL?.deletingLastPathComponent().path {
|
||||||
let dedicated = "\(exeDir)/battery_probe"
|
let dedicated = "\(exeDir)/battery_probe"
|
||||||
if FileManager.default.isExecutableFile(atPath: dedicated) {
|
if FileManager.default.isExecutableFile(atPath: dedicated) {
|
||||||
probeBin = dedicated
|
return (dedicated, [])
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if probeBin == nil, let exePath = Bundle.main.executablePath, FileManager.default.isExecutableFile(atPath: exePath) {
|
// 2. App bundle path in project directory
|
||||||
probeBin = exePath
|
let bundleProbe = "/Users/autli/Documents/blts_tracker/BLTS Tracker.app/Contents/MacOS/battery_probe"
|
||||||
probeArgs = ["--battery-probe"]
|
if FileManager.default.isExecutableFile(atPath: bundleProbe) {
|
||||||
|
return (bundleProbe, [])
|
||||||
}
|
}
|
||||||
|
|
||||||
guard let binary = probeBin else { return }
|
// 3. Current executable only if named blts_tracker
|
||||||
|
if let exePath = Bundle.main.executablePath,
|
||||||
|
exePath.hasSuffix("blts_tracker"),
|
||||||
|
FileManager.default.isExecutableFile(atPath: exePath) {
|
||||||
|
return (exePath, ["--battery-probe"])
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
public func pollSubprocessProbe() {
|
||||||
|
guard !isProbeRunning else { return }
|
||||||
|
|
||||||
|
if !BluetoothTracker.checkBluetoothPower() {
|
||||||
|
applyPowerOffState()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
guard let (binary, probeArgs) = resolveProbeBinary() else { return }
|
||||||
|
|
||||||
isProbeRunning = true
|
isProbeRunning = true
|
||||||
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
|
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
|
||||||
|
|
@ -124,8 +108,8 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
proc.standardOutput = pipe
|
proc.standardOutput = pipe
|
||||||
do {
|
do {
|
||||||
try proc.run()
|
try proc.run()
|
||||||
proc.waitUntilExit()
|
|
||||||
let data = pipe.fileHandleForReading.readDataToEndOfFile()
|
let data = pipe.fileHandleForReading.readDataToEndOfFile()
|
||||||
|
proc.waitUntilExit()
|
||||||
if let output = String(data: data, encoding: .utf8), !output.isEmpty {
|
if let output = String(data: data, encoding: .utf8), !output.isEmpty {
|
||||||
self?.parseProbeOutput(output)
|
self?.parseProbeOutput(output)
|
||||||
}
|
}
|
||||||
|
|
@ -181,7 +165,7 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
DispatchQueue.main.async { [weak self] in
|
let applyBlock = { [weak self] in
|
||||||
guard let self = self else { return }
|
guard let self = self else { return }
|
||||||
if !powerOn {
|
if !powerOn {
|
||||||
self.applyPowerOffState()
|
self.applyPowerOffState()
|
||||||
|
|
@ -189,6 +173,12 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
self.applyProbeDevices(devMap)
|
self.applyProbeDevices(devMap)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if Thread.isMainThread {
|
||||||
|
applyBlock()
|
||||||
|
} else {
|
||||||
|
DispatchQueue.main.async(execute: applyBlock)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func applyPowerOffState() {
|
private func applyPowerOffState() {
|
||||||
|
|
@ -278,6 +268,9 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Enrich connected devices from IOKit
|
||||||
|
enrichFromIORegistry(devices: &devices)
|
||||||
|
|
||||||
let foundActive = devices.first(where: { $0.isConnected && $0.isAudioDevice })
|
let foundActive = devices.first(where: { $0.isConnected && $0.isAudioDevice })
|
||||||
?? devices.first(where: { $0.isConnected })
|
?? devices.first(where: { $0.isConnected })
|
||||||
|
|
||||||
|
|
@ -311,9 +304,13 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
}
|
}
|
||||||
|
|
||||||
public func refreshNow() {
|
public func refreshNow() {
|
||||||
|
if !BluetoothTracker.checkBluetoothPower() {
|
||||||
|
applyPowerOffState()
|
||||||
|
} else {
|
||||||
updateDeviceList()
|
updateDeviceList()
|
||||||
pollSubprocessProbe()
|
pollSubprocessProbe()
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private func setupBluetoothListeners() {
|
private func setupBluetoothListeners() {
|
||||||
let notificationNames = [
|
let notificationNames = [
|
||||||
|
|
@ -322,9 +319,7 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
"IOBluetoothDeviceNotification",
|
"IOBluetoothDeviceNotification",
|
||||||
"IOBluetoothDeviceServicesResolvedNotification",
|
"IOBluetoothDeviceServicesResolvedNotification",
|
||||||
"IOBluetoothDeviceNameChangedNotification",
|
"IOBluetoothDeviceNameChangedNotification",
|
||||||
"IOBluetoothHandsFreeDeviceDidUpdateNotification",
|
"IOBluetoothHandsFreeDeviceDidUpdateNotification"
|
||||||
"com.apple.Bluetooth.status",
|
|
||||||
"com.apple.bluetooth.status"
|
|
||||||
]
|
]
|
||||||
|
|
||||||
for name in notificationNames {
|
for name in notificationNames {
|
||||||
|
|
@ -334,39 +329,18 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
name: NSNotification.Name(name),
|
name: NSNotification.Name(name),
|
||||||
object: nil
|
object: nil
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
|
||||||
DistributedNotificationCenter.default().addObserver(
|
DistributedNotificationCenter.default().addObserver(
|
||||||
self,
|
self,
|
||||||
selector: #selector(handleBluetoothChange),
|
selector: #selector(handleBluetoothChange),
|
||||||
name: NSNotification.Name(name),
|
name: NSNotification.Name("com.apple.Bluetooth.status"),
|
||||||
object: nil
|
object: nil
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
private func setupAudioListeners() {
|
|
||||||
var address = AudioObjectPropertyAddress(
|
|
||||||
mSelector: kAudioHardwarePropertyDefaultOutputDevice,
|
|
||||||
mScope: kAudioObjectPropertyScopeGlobal,
|
|
||||||
mElement: kAudioObjectPropertyElementMain
|
|
||||||
)
|
|
||||||
AudioObjectAddPropertyListenerBlock(
|
|
||||||
AudioObjectID(kAudioObjectSystemObject),
|
|
||||||
&address,
|
|
||||||
DispatchQueue.main
|
|
||||||
) { [weak self] _, _ in
|
|
||||||
self?.refreshNow()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@objc private func handleBluetoothChange() {
|
@objc private func handleBluetoothChange() {
|
||||||
DispatchQueue.main.async { [weak self] in
|
refreshNow()
|
||||||
self?.refreshNow()
|
|
||||||
}
|
|
||||||
for delay in [0.2, 0.5, 1.0] {
|
|
||||||
DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in
|
|
||||||
self?.refreshNow()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public func updateDeviceList() {
|
public func updateDeviceList() {
|
||||||
|
|
@ -379,44 +353,33 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
}
|
}
|
||||||
|
|
||||||
var updatedList: [BluetoothDeviceModel] = []
|
var updatedList: [BluetoothDeviceModel] = []
|
||||||
let activeAudioName = getActiveCoreAudioDeviceName()
|
|
||||||
|
|
||||||
// 1. Scan IOBluetooth paired devices
|
// 1. Scan IOBluetooth paired devices catalogue
|
||||||
if let pairedDevices = IOBluetoothDevice.pairedDevices() as? [IOBluetoothDevice] {
|
if let pairedDevices = IOBluetoothDevice.pairedDevices() as? [IOBluetoothDevice] {
|
||||||
for pairedDev in pairedDevices {
|
for pairedDev in pairedDevices {
|
||||||
let address = pairedDev.addressString ?? UUID().uuidString
|
let address = pairedDev.addressString ?? UUID().uuidString
|
||||||
let device = IOBluetoothDevice(addressString: address) ?? pairedDev
|
let name = pairedDev.nameOrAddress ?? "Unknown Device"
|
||||||
let name = device.nameOrAddress ?? pairedDev.nameOrAddress ?? "Unknown Device"
|
let majorClass = UInt32(pairedDev.deviceClassMajor)
|
||||||
|
let minorClass = UInt32(pairedDev.deviceClassMinor)
|
||||||
// Actively sync latest attributes from bluetoothd
|
let isAudio = (majorClass == 4) || isLikelyHeadphones(name: name, minorClass: minorClass, majorClass: majorClass)
|
||||||
syncFromServer(device: device)
|
|
||||||
if device !== pairedDev {
|
|
||||||
syncFromServer(device: pairedDev)
|
|
||||||
}
|
|
||||||
|
|
||||||
let isAudioOutput = activeAudioName != nil && (
|
|
||||||
name.caseInsensitiveCompare(activeAudioName!) == .orderedSame ||
|
|
||||||
activeAudioName!.localizedCaseInsensitiveContains(name) ||
|
|
||||||
name.localizedCaseInsensitiveContains(activeAudioName!)
|
|
||||||
)
|
|
||||||
let isConnected = (device.isConnected() || pairedDev.isConnected())
|
|
||||||
|
|
||||||
let majorClass = UInt32(device.deviceClassMajor)
|
|
||||||
let minorClass = UInt32(device.deviceClassMinor)
|
|
||||||
let isAudio = (majorClass == 4) || isLikelyHeadphones(name: name, minorClass: minorClass, majorClass: majorClass) || isAudioOutput
|
|
||||||
|
|
||||||
var isMulti = false
|
var isMulti = false
|
||||||
let selMulti = Selector(("isMultiBatteryDevice"))
|
let selMulti = Selector(("isMultiBatteryDevice"))
|
||||||
if device.responds(to: selMulti) {
|
if pairedDev.responds(to: selMulti) {
|
||||||
let imp = device.method(for: selMulti)
|
let imp = pairedDev.method(for: selMulti)
|
||||||
let fn = unsafeBitCast(imp, to: BoolGetter.self)
|
let fn = unsafeBitCast(imp, to: BoolGetter.self)
|
||||||
isMulti = fn(device, selMulti)
|
isMulti = fn(pairedDev, selMulti)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IMPORTANT: Strictly preserve isConnected and battery from the authoritative probe!
|
||||||
|
// NEVER query stale in-process IOBluetoothDevice ivars to avoid flickering!
|
||||||
|
let existing = self.devices.first(where: { $0.address == address })
|
||||||
|
let isConn = existing?.isConnected ?? false
|
||||||
|
|
||||||
var model = BluetoothDeviceModel(
|
var model = BluetoothDeviceModel(
|
||||||
name: name,
|
name: name,
|
||||||
address: address,
|
address: address,
|
||||||
isConnected: isConnected,
|
isConnected: isConn,
|
||||||
isAudioDevice: isAudio,
|
isAudioDevice: isAudio,
|
||||||
isMultiBattery: isMulti,
|
isMultiBattery: isMulti,
|
||||||
majorClass: majorClass,
|
majorClass: majorClass,
|
||||||
|
|
@ -424,20 +387,19 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
lastUpdated: Date()
|
lastUpdated: Date()
|
||||||
)
|
)
|
||||||
|
|
||||||
if isConnected {
|
if isConn {
|
||||||
extractBatteryLevels(from: device, fallbackDevice: pairedDev, into: &model, isMulti: isMulti)
|
model.singleBattery = existing?.singleBattery
|
||||||
} else {
|
model.leftBattery = existing?.leftBattery
|
||||||
knownBatteries.removeValue(forKey: address)
|
model.rightBattery = existing?.rightBattery
|
||||||
|
model.caseBattery = existing?.caseBattery
|
||||||
|
model.combinedBattery = existing?.combinedBattery
|
||||||
}
|
}
|
||||||
|
|
||||||
updatedList.append(model)
|
updatedList.append(model)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. IOKit Registry enrich
|
// 2. Sort: Connected audio first
|
||||||
enrichFromIORegistry(devices: &updatedList)
|
|
||||||
|
|
||||||
// 3. Sort: Connected audio first
|
|
||||||
updatedList.sort { d1, d2 in
|
updatedList.sort { d1, d2 in
|
||||||
if d1.isConnected != d2.isConnected {
|
if d1.isConnected != d2.isConnected {
|
||||||
return d1.isConnected && !d2.isConnected
|
return d1.isConnected && !d2.isConnected
|
||||||
|
|
@ -448,29 +410,18 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
return d1.name.localizedCaseInsensitiveCompare(d2.name) == .orderedAscending
|
return d1.name.localizedCaseInsensitiveCompare(d2.name) == .orderedAscending
|
||||||
}
|
}
|
||||||
|
|
||||||
|
self.devices = updatedList
|
||||||
|
|
||||||
let foundActive = updatedList.first(where: { $0.isConnected && $0.isAudioDevice })
|
let foundActive = updatedList.first(where: { $0.isConnected && $0.isAudioDevice })
|
||||||
?? updatedList.first(where: { $0.isConnected })
|
?? updatedList.first(where: { $0.isConnected })
|
||||||
|
|
||||||
let newPercent = foundActive?.primaryBatteryPercent
|
|
||||||
let newName = foundActive?.name ?? ""
|
|
||||||
let newConnected = foundActive?.isConnected == true
|
|
||||||
|
|
||||||
let applyUpdate = { [weak self] in
|
|
||||||
guard let self = self else { return }
|
|
||||||
self.objectWillChange.send()
|
|
||||||
self.devices = updatedList
|
|
||||||
self.activeHeadphone = foundActive
|
self.activeHeadphone = foundActive
|
||||||
self.currentBatteryPercent = newPercent
|
self.currentBatteryPercent = foundActive?.primaryBatteryPercent
|
||||||
self.currentDeviceName = newName
|
self.currentDeviceName = foundActive?.name ?? ""
|
||||||
self.isConnected = newConnected
|
self.isConnected = (foundActive?.isConnected == true)
|
||||||
NotificationCenter.default.post(name: BluetoothTracker.didUpdateNotification, object: self)
|
|
||||||
}
|
|
||||||
|
|
||||||
if Thread.isMainThread {
|
self.objectWillChange.send()
|
||||||
applyUpdate()
|
NotificationCenter.default.post(name: BluetoothTracker.didUpdateNotification, object: self)
|
||||||
} else {
|
|
||||||
DispatchQueue.main.async(execute: applyUpdate)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public func getActiveCoreAudioDeviceName() -> String? {
|
public func getActiveCoreAudioDeviceName() -> String? {
|
||||||
|
|
@ -533,64 +484,6 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
private func extractBatteryLevels(from device: IOBluetoothDevice, fallbackDevice: IOBluetoothDevice? = nil, into model: inout BluetoothDeviceModel, isMulti: Bool) {
|
|
||||||
func getBatteryValue(from dev: IOBluetoothDevice, selectorName: String) -> Int? {
|
|
||||||
let sel = Selector((selectorName))
|
|
||||||
if dev.responds(to: sel) {
|
|
||||||
let imp = dev.method(for: sel)
|
|
||||||
let fn = unsafeBitCast(imp, to: IntBatteryGetter.self)
|
|
||||||
let val = fn(dev, sel)
|
|
||||||
if val > 0 && val <= 100 {
|
|
||||||
return val
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let selPeer = Selector(("peer"))
|
|
||||||
if dev.responds(to: selPeer),
|
|
||||||
let peer = dev.perform(selPeer)?.takeUnretainedValue() as? NSObject {
|
|
||||||
let pSel = Selector((selectorName))
|
|
||||||
if peer.responds(to: pSel) {
|
|
||||||
let imp = peer.method(for: pSel)
|
|
||||||
let fn = unsafeBitCast(imp, to: IntBatteryGetter.self)
|
|
||||||
let val = fn(peer, pSel)
|
|
||||||
if val > 0 && val <= 100 {
|
|
||||||
return val
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func query(selectorName: String) -> Int? {
|
|
||||||
return getBatteryValue(from: device, selectorName: selectorName)
|
|
||||||
?? (fallbackDevice != nil ? getBatteryValue(from: fallbackDevice!, selectorName: selectorName) : nil)
|
|
||||||
}
|
|
||||||
|
|
||||||
let addr = model.address
|
|
||||||
|
|
||||||
if isMulti {
|
|
||||||
model.leftBattery = query(selectorName: "batteryPercentLeft")
|
|
||||||
model.rightBattery = query(selectorName: "batteryPercentRight")
|
|
||||||
model.caseBattery = query(selectorName: "batteryPercentCase")
|
|
||||||
model.combinedBattery = query(selectorName: "batteryPercentCombined")
|
|
||||||
model.singleBattery = query(selectorName: "batteryPercentSingle") ?? query(selectorName: "headsetBattery")
|
|
||||||
} else {
|
|
||||||
if let probeBatt = knownBatteries[addr], probeBatt > 0 && probeBatt <= 100 {
|
|
||||||
model.singleBattery = probeBatt
|
|
||||||
} else {
|
|
||||||
let single = query(selectorName: "batteryPercentSingle")
|
|
||||||
?? query(selectorName: "headsetBattery")
|
|
||||||
?? query(selectorName: "batteryPercentCombined")
|
|
||||||
?? query(selectorName: "batteryPercentLeft")
|
|
||||||
?? query(selectorName: "batteryPercentRight")
|
|
||||||
if let single = single {
|
|
||||||
knownBatteries[addr] = single
|
|
||||||
model.singleBattery = single
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private func enrichFromIORegistry(devices: inout [BluetoothDeviceModel]) {
|
private func enrichFromIORegistry(devices: inout [BluetoothDeviceModel]) {
|
||||||
let matching = IOServiceMatching("AppleDeviceManagementHIDEventService")
|
let matching = IOServiceMatching("AppleDeviceManagementHIDEventService")
|
||||||
var iterator: io_iterator_t = 0
|
var iterator: io_iterator_t = 0
|
||||||
|
|
@ -613,6 +506,9 @@ public final class BluetoothTracker: ObservableObject {
|
||||||
let battCase = dict["BatteryPercentCase"] as? Int
|
let battCase = dict["BatteryPercentCase"] as? Int
|
||||||
|
|
||||||
for i in 0..<devices.count {
|
for i in 0..<devices.count {
|
||||||
|
// Only enrich if the device is actually connected!
|
||||||
|
guard devices[i].isConnected else { continue }
|
||||||
|
|
||||||
let matchByName = prodName != nil && devices[i].name.caseInsensitiveCompare(prodName!) == .orderedSame
|
let matchByName = prodName != nil && devices[i].name.caseInsensitiveCompare(prodName!) == .orderedSame
|
||||||
let matchByAddr = addr != nil && devices[i].address.replacingOccurrences(of: "-", with: ":").caseInsensitiveCompare(addr!.replacingOccurrences(of: "-", with: ":")) == .orderedSame
|
let matchByAddr = addr != nil && devices[i].address.replacingOccurrences(of: "-", with: ":").caseInsensitiveCompare(addr!.replacingOccurrences(of: "-", with: ":")) == .orderedSame
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue