Необходимо поддерживать соединение с устройством BLE при переходе к другому контроллеру просмотра swift - PullRequest
0 голосов
/ 14 июля 2020

У меня есть два контроллера просмотра, и мне нужно показать одно значение из устройства ble в одном v c и другое значение из устройства ble на другом v c. В каждом v c я написал код для чтения и записи значения с устройства. Но проблема связана с переходом с одного v c на другое устройство, которое снова было подключено / отключено. Пожалуйста, помогите написать код для чтения и записи из ble, который будет отображать значения на каждом v c, поддерживая соединение с устройством ble .

Вот мой код


extension DeviceDetailsViewController: CBCentralManagerDelegate, CBPeripheralDelegate {
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        var msg = ""
        switch central.state {
        case .poweredOff:
            msg = "Bluetooth is Off"
        case .poweredOn:
            msg = "Bluetooth is On"
            manager.scanForPeripherals(withServices: nil, options: nil)
        case .unsupported:
            msg = "Not Supported"
        default:
            msg = ""
        }
        print("STATE: " + msg)
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        //you are going to use the name here down here ⇩
        if peripheral.name == peripheralName { //if is it my peripheral, then connect
            self.showHUD()
            self.myBluetoothPeripheral = peripheral     //save peripheral
            self.myBluetoothPeripheral.delegate = self
            //manager.stopScan()                          //stop scanning for peripherals
            manager.connect(myBluetoothPeripheral, options: nil) //connect to my peripheral
        }
    }
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        isMyPeripheralConected = true //when connected change to true
        myBluetoothPeripheral.discoverServices(nil)
    }
    
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        
        isMyPeripheralConected = false //and to falso when disconnected
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        
        if let servicePeripheral = peripheral.services as [CBService]? { //get the services of the perifereal
            for service in servicePeripheral {
                //Then look for the characteristics of the services
                peripheral.discoverCharacteristics(nil, for: service)
            }
        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        print("5")
        if let characterArray = service.characteristics as [CBCharacteristic]? {
            for cc in characterArray {
                //  if(cc.uuid.uuidString == "FFE1") { //properties: read, write
                //if you have another BLE module, you should print or look for the characteristic you need.
                myCharacteristic = cc //saved it to send data in another function.
                peripheral.readValue(for: cc) //to read the value of the characteristic
                peripheral.setNotifyValue(true, for: myCharacteristic)
                //  }
                writeValue()
            }
        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        print("7")
        if characteristic.uuid.uuidString == "6E400003-B5A3-F393-E0A9-E50E24DCCA9E" {
            if let readValue = characteristic.value {
                if let datastring = NSString(data: readValue, encoding: String.Encoding.utf8.rawValue) {
                    firmWare = datastring as String
                    if firmWare == "" {
                        myBluetoothPeripheral.delegate = self
                        manager.connect(myBluetoothPeripheral)
                    } else {
                        isStopLoader = true
                        tblDetails.reloadData()
                    }
                }
            }
        }
        if characteristic.uuid.uuidString == "2A19" {
            if let readValue = characteristic.value {
                let batteryPercentage = readValue.compactMap({ String(format: "%02x", $0) }).joined()
                if batteryPercentage < "60" {
                    batteryStatus = "CHANGE"
                } else if batteryPercentage == "" {
                    batteryStatus = ""
                } else {
                    batteryStatus = "OK"
                }
                tblDetails.reloadData()
            }
        }
        self.dismissHUD()
    }
    //if you want to send an string you can use this function.
    func writeValue() {
        print("8")
        if isMyPeripheralConected { //check if myPeripheral is connected to send data
            //Do something
            let setCmnd = "GET_FW_VERSION"
            let dataToSend: Data = setCmnd.data(using: String.Encoding.utf8)!
            myBluetoothPeripheral.writeValue(dataToSend, for: myCharacteristic, type: CBCharacteristicWriteType.withResponse)
        } else {
            print("Not connected")
        }
    }
}

1 Ответ

1 голос
/ 14 июля 2020

Вы не должны реализовывать CBCentralManagerDelegate и CBPeripheralDelegate в своих UIViewController подклассах. Вместо этого создайте отдельный класс, который может обрабатывать задачи связи Bluetooth, а затем используйте этот объект из ваших контроллеров представления. Класс может называться, например, BluetoothManager.

Вы можете передать объект от одного контроллера представления к другому, сделать его синглтоном или сделать его доступным через другие шаблоны, на ваше усмотрение.

...