• iOS设置作为蓝牙外设


    一、 说明

    任意苹果设备都可以作为蓝牙外设进行设置。
    苹果蓝牙后台的限制,原本广播会有两个段分别是localName和serviceUUID这两块,但现在后台广播时,是不发送在这两段的。

    二、设置蓝牙外设

    1. 初始化外设中心

    let peripheralManager = CBPeripheralManager.init(delegate: self, queue: DispatchQueue.main)
    
    • 1

    2. 创建外设服务

    public func setupServiceAndCharacteristics() {
            // 创建服务
            let serviceID = CBUUID(string: kServiceUUID)
            let service = CBMutableService(type: serviceID, primary: true)
            // 创建服务中的特征
            let characteristicID = CBUUID(string: kChARACTERISTICUUID)
            let characteristic = CBMutableCharacteristic(type: characteristicID, properties: [.read, .write, .notify], value: nil, permissions: [.readable, .writeable])
            // 特征添加进服务
            service.characteristics = [characteristic]
            // 服务加入管理
            self.peripheralManager?.add(service)
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    3. 获取外设蓝牙状态

    let tempState = self.peripheralManager?.state ?? .unknown
    
    • 1

    4. 发送蓝牙数据

    let sendSuccess: Bool = self.peripheralManager.updateValue(self.textField.text.data(using: NSUTF8StringEncoding), forCharacteristic: self.characteristic, onSubscribedCentrals: nil)
    
    • 1

    三、外设代理

    CBPeripheralManagerDelegate

    1. 状态变更回调

        func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
            print(peripheral.state)
            delegate?.peripheralUpdateState(peripheral)
        }
    
    • 1
    • 2
    • 3
    • 4

    2. 中心设备读取数据的时候回调

        func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
            // 请求中的数据,这里把文本框中的数据发给中心设备
    //        request.value = self.textField.text.data(using: NSUTF8StringEncoding)
            // 成功响应请求
    //        peripheral.respondToRequest(request, withResult: CBATTErrorSuccess)
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    3. 中心设备写入数据的时候回调

        func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
            // 写入数据的请求
            let request = requests.last
            
            let data = request?.value
            delegate?.peripheralDidReceiveWrite(data)
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    4. 订阅提示

        func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
            print(#function)
        }
        
        // 取消订阅回调
        func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) {
            print(#function)
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    四、发送广播数据

    1. 发送不同广播

    self.peripheralManager?.startAdvertising(periData)
    
    • 1

    2. beacon广播

    注意⚠️:测试时beacon广播CLBeacon未检测到iPhone设备。 即使使用 Turning an iOS device into an iBeacon device 也没有结果(如果帮助不胜感激)

    /// 开始发送广播
        public func startBroadcasting(major: UInt16 = 0, minor: UInt16 = 0, peripheralData: [String: Any]? = nil) {
            // 为beacon基站创建一个唯一标示
            guard let myUUID = UUID(uuidString: kBeaconUUIDString) else {
                return
            }
            
            let constraint = CLBeaconIdentityConstraint(uuid: myUUID, major: major, minor: minor)
            let myBeaconRegion = CLBeaconRegion.init(beaconIdentityConstraint: constraint, identifier: kBeaconidentifier)
            
            // 获取该Beacon区域的信号信息
            var periData = myBeaconRegion.peripheralData(withMeasuredPower: nil) as? [String: Any]
            peripheralData?.forEach { (key: String, value: Any) in
                periData?[key] = value
            }
            // 创建并广播Beacon信号
            self.peripheralManager?.startAdvertising(periData)
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    3. 停止广播

    self.peripheralManager?.stopAdvertising()
    
    • 1
  • 相关阅读:
    【2】CH347应用--在OpenOCD添加CH347-JTAG接口
    设计实例07-同步复位以及异步复位
    嵌入式开发:5个修订控制最佳实践
    dll文件缺失,ps,pr无法打开,游戏运行不了如何解决
    从制造到“智造”,看科聪控制系统如何赋能汽车行业智能生产
    PlantUML——类图(持续更新)
    爱普生机器人修改IP
    .NET周刊【1月第2期 2024-01-21】
    UG\NX二次开发 获取装配部件的相关信息UF_ASSEM_ask_component_data
    c#中判断类是否继承于泛型基类
  • 原文地址:https://blog.csdn.net/guoxulieying/article/details/133038983