适用于iOS的基本BLE通信应用程序,带有快速

时间:2016-01-16 23:36:47

标签: ios swift bluetooth bluetooth-lowenergy

我对iOS编程和蓝牙协议都很陌生。 我找到了一个用swift编写的示例代码,并尝试修改它以使用我自己的蓝牙模块。我所拥有的模块是来自dorji的DBM01

我需要使用的服务是 FFF0 ,并且发送ASCII值的特征是 FFF1

当我在我的macbook上使用LightBlue应用程序并连接到我设计的板上,其上有DBM01模块时,我可以发送char值为“1”并得到预期的响应(打开LED )当我发送值为“0”时,它会关闭LED。

现在有了我的代码,我可以连接到DBM01模块。我可以打印它的名字。但是,我无法通过以下功能与其断开连接。我也不确定这是用于断开设备还是在设备断开时自动调用。无论如何,它无论如何都不起作用。

func centralManager(central: CBCentralManager,
            didDisconnectPeripheral peripheral: CBPeripheral,
            error: NSError?)

我的主要问题是我真的不明白我如何指定我感兴趣的服务和特性,并连接到具有它们的特定设备。

我也无法发送消息。当我尝试时,我得到预定义的错误,因为以下条件不成立

if writeCharacteristic != nil

以下是我的完整代码。

感谢您是否可以指出我在哪里做错了以及如何使用特定服务和特征信息连接到特定设备并发送数据。

//
//  ViewController.swift
//  bleSwift
//

import UIKit
import CoreBluetooth

class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {

    var centralManager: CBCentralManager!
    var peripheral: CBPeripheral!
    var writeCharacteristic: CBCharacteristic!
    var service: CBService!
    var characteristic: CBCharacteristic!

    var bluetoothAvailable = false
    let message = "1"

    @IBOutlet weak var deviceName: UILabel!
    @IBOutlet weak var ServiceName: UILabel!
    @IBOutlet weak var CharacteristicsName: UILabel!

    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)
    {
                // 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)
                peripheral.discoverServices([CBUUID(string: "FFF0")])
                print("CONNECTED!!")
                print(peripheral.name)
                deviceName.text = peripheral.name
    }



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

    }

    @IBAction func disconnectDevice(sender: AnyObject) {

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

    @IBAction func Scan(sender: AnyObject)
    {
        print("Scan")
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }



    @IBAction func Send(sender: AnyObject)
    {
        let data = message.dataUsingEncoding(NSUTF8StringEncoding)
        if writeCharacteristic != nil
        {
            print("Sent")
            peripheral!.writeValue(data!,  forCharacteristic: writeCharacteristic, type: CBCharacteristicWriteType.WithoutResponse)
        }
        else
        {
            print("Couldn't Send")
        }
    }


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

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


}

1 个答案:

答案 0 :(得分:4)

为了将数据发送到您的外围设备,您应该:

  1. 开始扫描。
  2. 在你的中央管理员代表中,你将收到已发现外围设备的didDiscoverPeripheral回调。将自己设置为其委托并连接到它:centralManager.connectPeripheral(...)
  3. 在委托中接收didConnectPeripheral。现在为这个外围设备调用discoverServices。
  4. 在您的代理中接收didDiscoverServices。最后,请为您的服务调用discoverCharacteristics。
  5. 您将在didDiscoverCharacteristic委托方法中获得特征。之后,您将能够将数据发送到外围设备的确切特征。
  6. 要断开外围设备,请调用方法centralManager.cancelPeripheralConnection(...)