Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic BLE communication app for iOS with swift

I am quite new to iOS programming and also to bluetooth protocol. I have found a sample code written in swift and trying to modify it to work with my own bluetooth module. The module I have is DBM01 from dorji.

The service I need to use is FFF0 and the characteristics is FFF1 for sending a ASCII value.

When I use the LightBlue app on my macbook and connect to the board I have designed, which has the DBM01 module on it, I can send the char value of "1" and I get the expected response (Turning on a LED) and when I send value of "0" it turns the LED off.

Now with the code I have, I can connect to the DBM01 module. I can print its name. However, I cannot disconnect from it with the following function. I am also not sure if this is for disconnecting from the device or it is called automatically when the device is disconnected. Regardless, it does not work either way.

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

My main problem is I really didn't understand how I specify the service and the characteristics that I am interested in and connect to specific device that has them.

I am also unable to send a message. When I try I got the predefined error, since the following condition did't hold

if writeCharacteristic != nil

Below is my full code.

Appreciate if you can point out where I am doing wrong and how I can achieve connecting to specific device with specific service and characteristics information and sending data.

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


}
like image 286
user1449456 Avatar asked Sep 26 '22 16:09

user1449456


1 Answers

In order to send data to your ble peripheral, you should:

  1. Start scanning.
  2. In your ble central manager delegate you'll recieve didDiscoverPeripheral callback with discovered peripheral. Set yourself as its delegate and connect to it: centralManager.connectPeripheral(...)
  3. Receive didConnectPeripheral in delegate. Now call discoverServices for this peripheral.
  4. Recieve didDiscoverServices in your delegate. Finaly, call discoverCharacteristics for your service.
  5. You'll recieve characteristic in didDiscoverCharacteristic delegate method. After that, you'll be able to send data to exact characteristic of your peripheral.
  6. To disconnect peripheral, call method centralManager.cancelPeripheralConnection(...)
like image 80
skorolkov Avatar answered Oct 20 '22 16:10

skorolkov