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

use*_*456 5 bluetooth ios bluetooth-lowenergy swift

我对iOS编程和蓝牙协议都很陌生.我找到了一个用swift编写的示例代码,并尝试修改它以使用我自己的蓝牙模块.我有这个模块是DBM01从道尔吉.

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

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

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

func centralManager(central: CBCentralManager,
            didDisconnectPeripheral peripheral: CBPeripheral,
            error: NSError?)
Run Code Online (Sandbox Code Playgroud)

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

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

if writeCharacteristic != nil
Run Code Online (Sandbox Code Playgroud)

以下是我的完整代码.

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

//
//  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.
    }


}
Run Code Online (Sandbox Code Playgroud)

小智 4

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

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