I am utilizing SwiftyBluetooth
in an iOS App, a closure wrapper to CoreBluetooth
. I’ve created a Bluetooth singleton wrapper the place I’ve helpful methodology which are chainable with PromiseKit
.
I am making an attempt to put in writing a way that founds the closest peripheral (primarily based on RSSI) and to make it extra strong, I wish to ‘discover the identical peripheral as the closest for x occasions in a row’ (with x a parameter).
That is the 2 methodology I’ve written.
The primary one merely search the closest peripheral and works nice.
func searchNearest(withService service: BluetoothService = .configuration,
timeout: TimeInterval = 5) -> Promise<(Peripheral,[String : Any])
{
return Promise { seal in
var nearestPeripheral: Peripheral? = nil
var advData: [String : Any] = [:]
var maxRSSI = -1000
SwiftyBluetooth.scanForPeripherals(withServiceUUIDs: [service.rawValue],
timeoutAfter: timeout)
{ scanResult in
change scanResult {
case .scanStarted:
break
case .scanResult(let peripheral, let advertisementData, let RSSI):
if let identify = advertisementData["kCBAdvDataLocalName"] as? String,
identify.rely > 5,
let rssi = RSSI
{
print("identify: (identify) , rssi: (rssi)")
if rssi > maxRSSI {
maxRSSI = rssi
nearestPeripheral = peripheral
advData = advertisementData
print("identify: (identify)")
}
}
break
case .scanStopped(let peripherals, let error):
print("stopped")
if let nearest = nearestPeripheral {
print("fulfill")
seal.fulfill((nearest,advData))
} else {
print("error: (error?.localizedDescription)")
seal.reject(NSError.init(area: "", code: 0))
}
break
}
}
}
}
The second has some time loop and name with await asyn the primary methodology:
func searchNearest(inARow: Int,
withService service: BluetoothService = .configuration,
timeout: TimeInterval = 3) -> Promise<(Peripheral,[String : Any])>
{
return Promise { seal in
Job {
let max = 100
var i = 0
var discovered = 0
var identify: String = ""
whereas discovered < inARow && i < max {
print("max: (max), i: (i), identify: (identify)")
let nearest = attempt await searchNearest(withService: service, timeout: timeout).async()
print("nearest (nearest.0.identify)")
if nearest.0.identify == identify {
discovered += 1
} else {
identify = nearest.0.identify ?? ""
discovered = 1
}
if discovered == inARow {
seal.fulfill(nearest)
}
i += 1
}
seal.reject(NSError.init(area: "", code: 0))
}
}
}
The issue is that the primary time that this line is executed all works fantastic
let nearest = attempt await searchNearest(withService: service, timeout: timeout).async()
however on the second flip, they by no means returns.
The scan bluetooth by no means terminate, however for positive I am passing a extremely quick timeout (3 seconds).
The place am I doing mistaken?
Thanks.