CoreBluetooth状态保持连接状态

时间:2019-04-16 03:53:39

标签: swift xcode bluetooth

进行连接时,状态始终为:“正在连接”。 我正在尝试将具有iOS 12.2的iPhone连接到类似于arduino(ESP32)的设备。 在具有蓝牙工具的iPhone上,连接正常。 我检查了类似的问题,但没有找到一个简洁的解决方案,我想我应该在最后一个实例中尝试使用另一个蓝牙框架。

我当前的代码是:

private var centralManager : CBCentralManager!
private var esp32 : CBPeripheral!
private var characteristics: CBCharacteristic?

var txCharacteristic : CBCharacteristic?
var rxCharacteristic : CBCharacteristic?
var characteristicASCIIValue = NSString()


func centralManagerDidUpdateState(_ central: CBCentralManager)
{
    if central.state == .poweredOn
    {
        print("Bluetooth is On")
        //Escaneo los dispositivos.
        centralManager.scanForPeripherals(withServices: nil, options: nil)
    }
    else
    {
        print("Bluetooth is not active")
    }
}

override func viewDidLoad()
{
    super.viewDidLoad()
    centralManager = CBCentralManager(delegate: self, queue: nil)
}

//Esta funcion es invocada cuando se escanean los dispositivos.
public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    //Si encontre el ESP32.
    if(peripheral.name == "ESP32")
    {
        print("\nName   : \(peripheral.name ?? "(No name)")")
        print("RSSI   : \(RSSI)")
        for ad in advertisementData
        {
            print("AD Data: \(ad)")
        }
        //Mantengo una referencia FUERTE al dispositivo.
        esp32 = peripheral
        //Detengo la busqueda.
        centralManager.stopScan()
        esp32.delegate = self
        //Seteo el delegado.
        //Me conecto al dispositivo.
        centralManager?.connect(esp32!, options: nil)
        /*https://developer.apple.com/documentation/corebluetooth/cbperipheralstate*/
        sleep(5)
        print(esp32.state.rawValue)
        //self.esp32.discoverServices([BLEService_UUID])
        //self.esp32?.writeValue(mensajeAdaptado, for: char, type: .withoutResponse)
        //self.esp32.writeValue(mensajeAdaptado!, for: characteristics[0],type: CBCharacteristicWriteType.withoutResponse)
    }

}

//En caso de que nos hayamos podido conectar al dispositivo, le decimos que somos el delegado del mismo, esto
//permitirá utilizar los métodos que inician con "peripheral", por último buscamos los servicios
//que el dispositivo tiene disponibles.
func centralManager(_central: CBCentralManager!, didConnectPeripheral peripheral: CBPeripheral!)
{
    print("Connected")
    self.esp32.delegate = self
    self.esp32.discoverServices(nil)

}

public func connectToPeripheral(peripheral: CBPeripheral) -> Bool
{

    if self.centralManager.state != .poweredOn
    {

        print("[ERROR] Couldn´t connect to peripheral")
        return false
    }

    print("[DEBUG] Connecting to peripheral: \(peripheral.identifier.uuidString)")

    self.centralManager.connect(peripheral, options: [CBConnectPeripheralOptionNotifyOnDisconnectionKey : NSNumber(value: true)])

    return true
}

}

0 个答案:

没有答案