1、蓝牙开发【中心模式】基础篇

一、 中心模式(Central):

蓝牙分为两种模式:peripheral和central(外设和中心),一般手机都会用来作为中心,去连接管理其他外设(比如智能手环、手表、智能家居)。

在开发中,中心模式主要流程为:

  1. 创建中心管理对象;
  2. 扫描外设(scan);
  3. 链接外设(connect);
  4. 扫描外设服务:
    • 获取外设服务(services);
    • 获取服务的特征(characteristics),如果需要,可以获取特征的描述符号和对应值。
  5. 利用特征进行数据交互,读写数据,订阅特征通知;
  6. 在不需要的时候,断开链接。

整体流程如下:


1、蓝牙开发【中心模式】基础篇_第1张图片
centralMode_flow.png

二、代码实现(Swift):

1. 创建中心管理对象

centralManager = CBCentralManager(delegate: self, queue: nil)
// 当前对象要实现 CBCentralManagerDelegate 协议方法:
// 手机蓝牙状态改变的代理方法
func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .poweredOn:
            // 手机蓝牙已打开
            // 只有当前cetral的状态处于 poweredOn 状态的时候,才可以进行蓝牙相关操作
            self.startScanPeripherals()
        case .poweredOff:
            fallthrough
        case .unauthorized:
            fallthrough
        case .unknown:
            fallthrough
        case .unsupported:
            fallthrough
        case .resetting:
            print("蓝牙还不可用~")
        }
}


// 发现外设时,代理回调方法
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        if advertisementData.keys.contains("kCBAdvDataLocalName") {
            let name = advertisementData["kCBAdvDataLocalName"] as? String;
            print("发现外设:\(name ?? "null")")
        }
}

// 外设链接上时,代理回调方法
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        // 设置代理
        peripheral.delegate = self
        // 连接上之后,先发现他们的服务,发现服务时,会回调 peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) 代理方法
        peripheral.discoverServices(nil)
}

// 链接外设失败时,代理回调方法
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        print("连接失败:\(String(describing: error?.localizedDescription))")
}

2. 链接外设

// 连接外设,连接上之后,会回调func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral)代理方法
// 注意要持有你当前要链接的外设
self.peripheral = peripheral
centralManager.connect(peripheral, options: nil)

// 在外设链接上之后,进行扫描发现服务
// 外设链接上时,代理回调方法
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        // 设置代理
        peripheral.delegate = self
        // 连接上之后,先发现他们的服务,发现服务时,会回调 peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) 代理方法
        peripheral.discoverServices(nil)
}

// 如果发现服务,则会进入下面代理回调方法
public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        if error != nil {
            print("出错")
        } else {
            if let services = peripheral.services {
                for service in services {
                  // 记录已经发现的服务
                    self.services[service.uuid.uuidString] = service;
                 // 发现服务的特征 
                   peripheral.discoverCharacteristics(nil, for: service)
                }
            } 
        }
}

// 发现特征值之后,会进入下面代理回调方法
public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        if error != nil {
            print("出错")
        } else {
            self.discoveredServices.append(service)
            if let characteristics = service.characteristics {
                for characteristic in characteristics {
                    // 记录下发现的特征值
                    self.characteristics[characteristic.uuid.uuidString] = characteristic;
                    // 如果有通知属性,则订阅该特征
                    if characteristic.properties.contains(.notify) {
                        peripheral.setNotifyValue(true, for: characteristic)
                    }
                }
            }
        }
}

// 至此,链接设备完成,可以进行数据交互了

3. 读写数据

// 写数据
let data = Data(要写的数据)
let characteristic:CBCharacteristic = 要写到哪个特征里面去
// 写数据的类型
var type = CBCharacteristicWriteType.withResponse;
if characteristic.properties.contains(.writeWithoutResponse) {
     type = .withoutResponse;
}
// 注意,这里的数据长度,不能大于 外设 和 手机 支持的MTU,(单次蓝牙间隔发送的最大数据量)
// 一般低端一点的蓝牙,单次发送,最多发20字节
self.peripheral.writeValue(data, for: characteristic, type: type)



// 读数据,中心central获取外设的数据
// 一种方式是,自己主动去读取,一种是订阅了,外设往中心推
// 两种方式,都是需要外设做相应的支持
let characteristic:CBCharacteristic = 要从哪个特征读取数据
// 读取数据
self.peripheral.readValue(for: characteristic)

// 读取到数据,或者订阅推数据,都会从下面代理方法回调
public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        
        guard let data = characteristic.value else {
            return
        }

        print("\(self.name)(\(characteristic.uuid.uuidString)) recv data:\(data.hexEncodedString()))")
}

三、总结:

本次只是简单介绍了,整个中心模式(central)的基本流程,下一篇文章中会详细介绍每一个方法的细节和相关注意事项,并进行更加合理的封装(扫描链接模块)

你可能感兴趣的:(1、蓝牙开发【中心模式】基础篇)