其他分享
首页 > 其他分享> > iOS --蓝牙扫描、连接、读取数据

iOS --蓝牙扫描、连接、读取数据

作者:互联网

直接上代码 代码中有详细的注释 可以将代码复制到工具类中使用

import UIKit
@_exported import CoreBluetooth

enum ConnectMethod {
    case connect
    case restore
}
 
class BluetoothTool: NSObject {
    static var sharedBle = BluetoothTool()
    var centralManager:CBCentralManager?
    var periphherals = [String:CBPeripheral]()
    var character:CBCharacteristic? = nil
    var connectMethod:ConnectMethod = .connect
    var r_uuidString = "uuid" // 需要重新连接的设备标示字符串
    override init() {
        super.init()
        print("-------BluetoothTool初始化-----")
    }
   
    /**
     扫描
     */
    func scan() {
        if let manager = self.centralManager {
            getInfo(state: manager.state)
        } else {
            let options = ["CBCentralManagerOptionShowPowerAlertKey":false]
            centralManager = CBCentralManager(delegate: self, queue: .main, options: options)
        }
    }
    //停止扫描
    func stopScan() {
        if let manager = self.centralManager {
            if manager.isScanning {
                manager.stopScan()
            }
        }
    }
    
    //取消连接
    func cancelConnect() {
        if let manager = self.centralManager {
            if let p = self.periphherals[r_uuidString] {
                manager.cancelPeripheralConnection(p)
            }
        }
    }
    
    /**
     获取手机的蓝牙状态
     */
    func getInfo(state:CBManagerState) {
       
        if state == .poweredOn {
            print("手机蓝牙功能打开了")
           centralManager!.scanForPeripherals(withServices: nil, options: nil)
       }
        else {
           if state == .poweredOff {
                print("手机蓝牙功能没有打开")
            } else if state == .unauthorized {
                print("手机蓝牙功能没有权限,请前往设置。")
            } else if state == .unsupported {
                print("手机不支持蓝牙功能,请更换手机。")
             
            }
        }
 
    }
    //连接 设备
    func connectBindBLEDevice(_ hardware_id: Int? = nil, handler:((Bool, CBPeripheral)->())? = nil)
    {
        if let manager = self.centralManager {
            manager.connect(self.periphherals[r_uuidString]!, options: nil)
        }
    }
    
    func retricevePeripheral(_ uuid: UUID) -> CBPeripheral? {
        guard let manager = self.centralManager else {
            return nil
        }
        let peripherals = manager.retrievePeripherals(withIdentifiers: [uuid])
        
        if peripherals.count > 0 {
            let periphheral = peripherals.first!
            return periphheral
        }
        
        return nil
    }
   /**
     连接
     */
    func connect(peripheral:CBPeripheral,handler:((Bool, CBPeripheral)->())?) {
        self.connectMethod = .connect
        centralManager!.connect(peripheral, options: nil)
    }
    /**
     断开连接
     */
    func disConnect(peripheral:CBPeripheral) {
        centralManager!.cancelPeripheralConnection(peripheral)
    }
    //向蓝牙设备写入数据
    func writeDataToBle(str:String){
        if let c = character {
             if   c.properties.isEmpty  {
                //BLE设备接收的数据需要转为NSData类型
                 let data = str.data(using: String.Encoding.utf8)!
                //第一个参数:你要写入的数据,为data类型。
                //第二个参数:你要向哪个特征写入,一般就是属性为写入的那个特征。
                //第三个参数:你写入的方式,这个参数有两个枚举分别是:
                //withResponse //写入数据有回应
                //withoutResponse //写入数据没有回应
                if let p = self.periphherals[r_uuidString] {
                     p.writeValue(data , for: c, type: .withResponse)
                }
                
            }else{
                print("该字段不可写!")
            }
        }
        
    }
    
}

extension BluetoothTool:CBCentralManagerDelegate {
    //MARK:CBCentralManagerDelegate
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        getInfo(state: central.state)
    }
    
    /**
     发现符合要求的外设
     */
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData advertisement: [String : Any], rssi RSSI: NSNumber) {
        
     print("CBPeripheral == \(peripheral)")
     if let name = peripheral.name {
         print("蓝牙设备:", name)
             if name  == "xxxxxxxxx" { //这里判断是否是自己需要查找的设备
                 self.periphherals[r_uuidString] = peripheral
                 connectBindBLEDevice()
             }
        }
    }
    
    /**
     连接外设成功
     */
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("连接外设成功")
        if let name = peripheral.name {
           print(" 连接外设成功 name == \(name)")
        }
        //停止扫描
        peripheral.discoverServices(nil)
        self.stopScan()
    }
    
    /**
     连接失败
     */
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        if let name = peripheral.name {
            print("连接失败", name)
        }
 
    }
    
    /**
     断开连接
     */
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        print("断开连接",central)
        if let name = peripheral.name {
            if error != nil {
                print("重新连接")
            }else{
                print("name == \(name)")
            }
        }
 
    }}
extension BluetoothTool:CBPeripheralDelegate {
    /**
     找到服务
     */
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
       if let services = peripheral.services {
            for service in services {
                let serviceUUID = service.uuid.uuidString
                peripheral.discoverCharacteristics(nil, for: service)
                print("serviceUUID == \(serviceUUID)")
            }
        }
        
    }
    /**
     找到特征
     */
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        guard let characteristics = service.characteristics else {
            print("Bluetooth: unable to retrieve service characteristics")
            return
        }
       
        for characteristic in characteristics {
            let uuid = characteristic.uuid.uuidString
            print("uuid == \(uuid)")
            if uuid  == "xxxxxxx"{ //这里拿到硬件的特征值
                
            }
        }
    }
    
    /**
     从设备上 获取到 数据会调用此代理方法
     */

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        if let err = error {
            print("错误:", err)
        }
        if let data = characteristic.value {
               print("获取数据 == \(data)")
        }
    }
 
    /**使用 .withResponse的 成功写入后就会调用这个代理方法*/
    func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        print("写入数据")
     
    }
  
    
}

标签:读取数据,--,peripheral,iOS,let,func,print,CBPeripheral,name
来源: https://blog.csdn.net/weixin_43259805/article/details/123052397