简体   繁体   English

无法从iOS中的BLE设备获取数据/服务

[英]not getting data / services from BLE device in ios

I need to connect with a BLE device and then handle data as per sent via different button in it. 我需要连接BLE设备,然后按照通过其中的其他按钮发送的数据进行处理。
For that I wrote following code. 为此,我编写了以下代码。

import CoreBluetooth
class HomeViewController: UIViewController,CBPeripheralDelegate,CBCentralManagerDelegate 
{
    var centralManager : CBCentralManager!
    var peri : CBPeripheral!
    override func viewDidLoad()
    {
        super.viewDidLoad()
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    func centralManagerDidUpdateState(central: CBCentralManager) {
        if central.state == .Unknown
        {
            print("Unknown")
        }
        else if central.state == .Unsupported
        {
            print("Unsupported")
        }
        else if central.state == .Unauthorized
        {
            print("Unauthorized")
        }
        else if central.state == .Resetting
        {
            print("Resetting")
        }
        else if central.state == .PoweredOn
        {
            print("Powered On")
            startScan()
        }
        else if central.state == .PoweredOff
        {
            print("Powered Off")
        }
    }
    func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
        print("Discovered: \(peripheral.name) at \(RSSI)")
        print("AdvertisementData:\(advertisementData)")

        if peri != peripheral
        {
            peri = peripheral
            centralManager.connectPeripheral(peripheral, options: nil)
        }
    }
    func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
        print("Failed to connect \(peripheral) cause of \(error)")
    }

    func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
        print("connected to \(peripheral)")
//        centralManager.stopScan()
        print("Available services:\(peripheral.services)")
    }
    func peripheral(peripheral: CBPeripheral, didDiscoverIncludedServicesForService service: CBService, error: NSError?) {
        print("Services\(service) and error\(error)")
    }
    func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
        print("Services and error\(error)")
    }
    func startScan(){
        print("Scanning...")
        centralManager.scanForPeripheralsWithServices(nil, options: nil)
    }
}

And here is my Log for this code. 这是此代码的日志。

Powered On
Scanning...
Discovered: Optional("**** BLE") at 127
AdvertisementData:["kCBAdvDataIsConnectable": 1, "kCBAdvDataServiceUUIDs": (
    1802
)]
connected to <CBPeripheral: 0x12756d910, identifier = 6197****-EB0A-F1E8-BEF4-1AFAC629C5BC, name = **** BLE, state = connected>
Available services:nil

This is output is generated when one button is clicked from BLE device. 当从BLE设备中单击一个按钮时,将生成此输出。 But I am unable to receive or read data when another button is clicked. 但是单击另一个按钮后,我无法接收或读取数据。
Android developer of same app has integrated with both button. 同一应用的Android开发人员已将这两个按钮集成在一起。
So there is no any problem in device. 因此,设备没有任何问题。
Can anyone help me to guide where I'm going wrong in this code?? 谁能帮助我指导这段代码在哪里出问题了?

Pandafox 's answer is perfect just one thing is missing from it. Pandafox的答案是完美的,只是缺少一件事。
Which is setting delegate of peripheral. 这是设置外围设备的代表。

Here is the complete code to discover peripheral, connect to it and discover its services and characteristics. 这是发现外围设备,连接外围设备并发现其服务和特性的完整代码。

1.Connect peripheral 1.连接外围设备

func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
    print("Discovered: \(peripheral.name) at \(RSSI)")
    print("AdvertisementData:\(advertisementData)")

    if peri != peripheral
    {
        peri = peripheral
        peri.delegate = self
        centralManager.connectPeripheral(peri, options: nil)
    }
}
  1. Connection failure or success 连接失败或成功

     func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) { print("Failed to connect \\(peripheral) cause of \\(error)") } func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) { print("connected to \\(peripheral)") // centralManager.stopScan() peripheral.discoverServices(nil) } 

3.DiscoverServices 3,发现服务

func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
        print("Services:\(peripheral.services) and error\(error)")
        if let services = peripheral.services {
            for service in services {
                peripheral.discoverCharacteristics(nil, forService: service)
            }
        }
    }
  1. Discover Characteristics and set notification 发现特征并设置通知

     func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) { print("peripheral:\\(peripheral) and service:\\(service)") for characteristic in service.characteristics! { peripheral.setNotifyValue(true, forCharacteristic: characteristic) } } 
  2. Handle notification for update value of characteristics 处理有关特征更新值的通知

     func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) { print("characteristic changed:\\(characteristic)") } 

You also have to discover the services and characteristics after connecting to the device. 连接到设备后,您还必须发现服务和特征。

For example, in your "didConnectPeripheral" method, you will have to do something like: 例如,在您的“ didConnectPeripheral”方法中,您将必须执行以下操作:

 func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
    print("connected to \(peripheral)")
    peripheral.delegate = self
    peripheral.discoverServices(nil)
    print("Discovering services!")
}

And then: 接着:

func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
    print("Discovered services: \(peripheral.services), Error\(error)")
    if let services = peripheral.services {
        for service in services {
            peripheral.discoverCharacteristics(nil, forService: service)
        }
    }
}

And then you have to handle each characteristic: 然后,您必须处理每个特征:

 func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError)

You must remember to store each characteristic manually, as they will be deallocated if you don't. 您必须记住手动存储每个特征,因为如果不存储,它们将被释放。

In order to receive streaming data (notifications) you will have to enable notify for each characteristic. 为了接收流数据(通知),您将必须为每个特征启用通知。

peripheral.setNotifyValue(true, forCharacteristic: characteristic)

You also have to implement: 您还必须实现:

 func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError)

Order to handle the incoming values. 命令处理传入的值。

As you can see, there's quite a bit of boiler plate code required to get started. 如您所见,开始时需要很多样板代码。

After connecting to the peripheral you have to call discoverServices on the peripheral with the UUID of the services you want to discover, you then have to discover the characteristics of the service. 连接到外围设备后,必须使用要discoverServices的服务的UUID调用外围设备上的discoverServices,然后才能发现服务的特征。 If you want updates when a button is clicked, you will have to turn notifications on for the characteristic corresponding to that button 如果要在单击按钮时进行更新,则必须打开与该按钮对应的特性的通知

I would highly recommend this link from apple for follow up reading if you still need help. 如果您仍需要帮助,我强烈建议您从Apple获得此链接以进行后续阅读。 It describes what you need to do step by step in a better fashion than I could ever describe here. 它以比我在此描述的方式更好的方式描述了您需要逐步执行的操作。

Apple BLE Guide Apple BLE指南

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM