【问题标题】:Unable to find BLE peripherals找不到 BLE 外围设备
【发布时间】:2015-11-29 23:28:39
【问题描述】:

我是 Xcode 的新手,我编写了一些代码来发现并连接到 BLE 模块 (Adafruit Bluefruit LE)。但是,扫描时,什么也找不到。 有什么帮助吗?

这是我的代码

import UIKit
import CoreBluetooth

class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {

    //let BLUEFRUIT_SERVICE = "DFB0"
    var centralManager: CBCentralManager!
    var connectedPeripheral : CBPeripheral!



    @IBAction func myButton(sender: UIButton) {
        print(sender.tag)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        centralManager=CBCentralManager(delegate: self, queue: nil)
    }

    func scanForDevice () {
        centralManager.scanForPeripheralsWithServices(nil, options: nil )
// I also tried with the following line, but I don't understand the use of BLUEFRUIT_SERVICE = "DFB0"
        //        centralManager.scanForPeripheralsWithServices([CBUUID(string: BLUEFRUIT_SERVICE)], options: nil)

    }

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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    //Central Manager delegates

    func centralManagerDidUpdateState(central: CBCentralManager) {
        print("central manager did updated started")

        switch(central.state){
        case .PoweredOff:
            print("Power is OFF")
            break

        case .Resetting:
            print("Resetting")
            break

        case .PoweredOn :
            print("Power is ON");
            break

        case.Unauthorized:
            print("Unauthorized")
            break

        case .Unsupported:
            print("Unsupported")
            break

        default:
            print("Unknown")
            break
        }
    }

}

【问题讨论】:

  • 什么时候打电话给scanForDevice?您应该在开机状态下调用它
  • 我也尝试了该选项,但仍然没有..

标签: ios swift bluetooth


【解决方案1】:

当您使用 LightBlue 等应用程序进行扫描时,您能否看到设备?

我在尝试连接到 Bluno 设备时遇到了类似的问题。随意看看我的代码,看看它是否适合你。目前很难编码以查找两个特定的 Bluno 设备,但如果找到正确的设备,您应该能够轻松更改它以进行连接。

https://github.com/FredLoh/BluetoothResearchProject

试试下面的代码。注意:您可能必须将设备名称(当前为 Bluno)以及 DF80 和 DF81 字符串更新为您的设备接受的任何内容。您可能还必须将其正确连接到您使用的任何接口。

import UIKit
import CoreBluetooth

class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {

  var centralManager: CBCentralManager!
  var connectedPeripheral: CBPeripheral!



  @IBAction func myButton(sender: UIButton) {
      print(sender.tag)
  }

  override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view, typically from a nib.

      centralManager=CBCentralManager(delegate: self, queue: nil)
  }

  func startScanning() {
    print("Started Scanning!")
    //Could add service UUID here to scan for only relevant services
    centralManager = CBCentralManager(delegate: self, queue: nil)
}

func sendMessage() {
    let message = "5"
    let data = message.dataUsingEncoding(NSUTF8StringEncoding)
    if terminalChar != nil {
        peripheral!.writeValue(data!,  forCharacteristic: terminalChar, type: CBCharacteristicWriteType.WithoutResponse)
    }
}

func peripheral(peripheral: CBPeripheral, didWriteValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
    print("Value was sent")
}

func discoverDevices() {
    print("discovering devices")
    centralManager.scanForPeripheralsWithServices(nil, options: nil)
}

func centralManagerDidUpdateState(central: CBCentralManager) {
    print("Checking state")
    switch (central.state) {
    case .PoweredOff:
        print("CoreBluetooth BLE hardware is powered off")

    case .PoweredOn:
        print("CoreBluetooth BLE hardware is powered on and ready")
        bluetoothAvailable = true;

    case .Resetting:
        print("CoreBluetooth BLE hardware is resetting")

    case .Unauthorized:
        print("CoreBluetooth BLE state is unauthorized")

    case .Unknown:
        print("CoreBluetooth BLE state is unknown");

    case .Unsupported:
        print("CoreBluetooth BLE hardware is unsupported on this platform");

    }
    if bluetoothAvailable == true {
        discoverDevices()
    }
}
func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
    //        print(peripheral)
    let deviceName = "Bluno"
    if let nameOfDeviceFound = peripheral.name {
        if (nameOfDeviceFound == deviceName) {
            print("Discovered \(deviceName)")
            print("")

            print(peripheral)
            // Stop scanning
            self.centralManager.stopScan()
            print("Stopped Scanning")
            // Set as the peripheral to use and establish connection
            self.peripheral = peripheral
            self.peripheral.delegate = self
            self.centralManager.connectPeripheral(peripheral, options: nil)
        }
        else {
            print("NOPE.EXE")
        }
    }
}

func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
    print("Did connect to peripheral.")
    print("")
    peripheral.delegate = self
    peripheral.discoverServices([CBUUID(string: "DFB0")])
    let state = peripheral.state == CBPeripheralState.Connected ? "yes" : "no"
    print("Connected:\(state)")

}

//    // Check if the service discovered is a valid IR Temperature Service
func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
    if(error != nil) {
        print(error?.description)
    }

    for svc in peripheral.services! {
        print("Service \(svc)\n")
        print("Discovering Characteristics for Service : \(svc)")
        peripheral.discoverCharacteristics([CBUUID(string: "DFB1")], forService: svc as CBService)
    }
}

func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
    if(error != nil) {
        print(error?.description)
    }
    for characteristic in service.characteristics! {
        if characteristic.UUID == CBUUID(string: "DFB1") {
            self.terminalChar = (characteristic as CBCharacteristic)
            peripheral.setNotifyValue(true, forCharacteristic: characteristic as CBCharacteristic)

            // Send notification that Bluetooth is connected and all required characteristics are discovered
            print("Found characteristic we were looking for!")
            print(peripheral.readValueForCharacteristic(characteristic as CBCharacteristic))

        }
    }
}

func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
    print("Failed to connect to peripheral.")
}

func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
    print("CONNECTION WAS DISCONNECTED")
}
}

【讨论】:

  • 我可以使用您的程序进行连接,但无法发送任何命令。事实上,我的 BLE 需要例如接收 char 'l' 来执行操作,我尝试更改消息功能但它不起作用。
  • 嘿@Raph,您需要更改消息函数和didDiscoverPeripheral、didConnectPeripheral 和didDiscoverServices。目前我正在寻找的 CBUUID 服务是 2222。我猜你的是 DF81。试一试,如果您需要任何帮助,请告诉我。
  • 感谢您的回复。其实我是 Xcode 的新手,所以我真的不知道在不同的函数中要改变什么以及如何确定 CBUUID...
  • 编辑我的帖子一秒钟。将发布我的旧布鲁诺代码
  • 嗨,我可以连接...但仍然无法发送任何命令:-/非常感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2017-04-23
  • 1970-01-01
  • 2019-04-30
  • 1970-01-01
  • 2017-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多