Приложение IOS не получает события пожара от устройства Bluetooth после подключения к нему - PullRequest
0 голосов
/ 02 ноября 2018

У меня есть устройство Bluetooth. Когда я запускаю устройство, приложение IOS получает событие пожара от него по методу func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) в advertisementData["kCBAdvDataLocalName"] Но когда я подключаю устройство Bluetooth BLE к своему приложению через centralManager.connect (heartRatePeripheral) , метод не получает пожара событие в любом из CBPeripheralDelegate методов. Пожалуйста, помогите мне, как получить событие после подключения устройства BLE с приложением IOS. Ниже мой полный код.

import UIKit
import CoreBluetooth

let heartRateServiceCBUUID = CBUUID(string: "FFC2")

class HRMViewController: UIViewController {

   @IBOutlet weak var heartRateLabel: UILabel!
   @IBOutlet weak var bodySensorLocationLabel: UILabel!

   var centralManager: CBCentralManager!
   var heartRatePeripheral: CBPeripheral!

   override func viewDidLoad() {
      super.viewDidLoad()

      centralManager = CBCentralManager(delegate: self, queue: nil)
      heartRateLabel.font = UIFont.monospacedDigitSystemFont(ofSize: 
      heartRateLabel.font!.pointSize, weight: .regular)
   }

   func onHeartRateReceived(_ heartRate: Int) {
       heartRateLabel.text = String(heartRate)
       print("BPM: \(heartRate)")
   }
}

extension HRMViewController: CBCentralManagerDelegate {
   func centralManagerDidUpdateState(_ central: CBCentralManager) {
   }

   func centralManager(_ central: CBCentralManager, didDiscover  
   peripheral: CBPeripheral, advertisementData: [String : Any], rssi 
   RSSI: NSNumber) {
       if advertisementData["kCBAdvDataLocalName"] as? String == 
           "SPS026A" {
           print(advertisementData["kCBAdvDataLocalName"])
           let data = 
            advertisementData[CBAdvertisementDataManufacturerDataKey]
            print("data ==\(data)")
            heartRatePeripheral = peripheral
            centralManager.connect(heartRatePeripheral)
        }
   }

   func centralManager(_ central: CBCentralManager, didConnect 
   peripheral: CBPeripheral) {
        print("Connected!")
        heartRatePeripheral.discoverServices([])
        heartRatePeripheral.delegate = self
    }
}

extension HRMViewController: CBPeripheralDelegate {
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices 
    error: Error?) {
         guard let services = peripheral.services else { return }
         for service in services {
             print(service)
             peripheral.discoverCharacteristics(nil, for: service)
         }
     }

     func peripheralDidUpdateName(_ peripheral: CBPeripheral) {

     }

     func peripheral(_ peripheral: CBPeripheral, 
     didDiscoverCharacteristicsFor service: CBService, error: Error?) 
     {
          guard let characteristics = service.characteristics else { 
          return }
          for characteristic in characteristics {
               if characteristic.properties.contains(.read) {
                    print("\(service): service : \ . 
                    (characteristic.uuid): properties contains .read")
                    peripheral.readValue(for: characteristic)
                }
               if characteristic.properties.contains(.notify) {
                     print("\(service): service : \ 
                     (characteristic.uuid): properties contains 
                     .notify")
                      peripheral.setNotifyValue(true, for: 
                      characteristic)
                }
            }
       }

       func peripheral(_ peripheral: CBPeripheral, didOpen channel: 
       CBL2CAPChannel?, error: Error?) {

       }

       func peripheralIsReady(toSendWriteWithoutResponse peripheral: 
       CBPeripheral) {

       }

       func peripheral(_ peripheral: CBPeripheral, 
       didUpdateNotificationStateFor characteristic: CBCharacteristic, 
       error: Error?) {
             print("Unhandled Characteristic UUID: \(characteristic)")
       }

       func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor 
       characteristic: CBCharacteristic, error: Error?) {
             print("Unhandled Characteristic UUID: \(characteristic)")
       }
   }

1 Ответ

0 голосов
/ 02 ноября 2018

Чтобы обнаружить все службы периферийного устройства, вы должны передать nil в discoverServices, а не в пустой массив.

heartRatePeripheral.discoverServices(nil)

Передавая пустой массив, вы говорите, что не хотите открывать какие-либо службы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...