美文网首页
ios app作为蓝牙外设

ios app作为蓝牙外设

作者: liang1030 | 来源:发表于2019-12-18 21:06 被阅读0次
//
//  BLEPeripheralManager.swift
//  
//
//  Created by liang on 2019/1/17.
//  Copyright © 2019 liang. All rights reserved.
//

import UIKit
import CoreBluetooth

//可以使用命令生成128位的UUID
// liangdeMac-mini:~ liang$ uuidgen
// AC586E87-17F8-42D0-818D-E6B0ECA954C0

private let Service_UUID: String = ""
private let Characteristic_UUID: String = ""

class BLEPeripheralManager: NSObject {
    
    private var peripheralManager: CBPeripheralManager?
    private var characteristic: CBMutableCharacteristic?
    private(set) var BLEState:CBManagerState?
    
    //蓝牙状态变更回调
    typealias BLEStateBlock = () -> ()
    var staseCallback: BLEStateBlock?
    
    //单例
    static let shared = BLEPeripheralManager()
    
    private override init() {
        super.init()
        
        peripheralManager = CBPeripheralManager.init(delegate: self, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey:false])
    }

}

extension BLEPeripheralManager: CBPeripheralManagerDelegate {
    
    // 蓝牙状态
    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        BLEState = peripheral.state
        if staseCallback != nil {
            staseCallback!()
        }
        switch peripheral.state {
        case .unknown:
            print("未知的")
        case .resetting:
            print("重置中")
        case .unsupported:
            print("不支持")
        case .unauthorized:
            print("未验证")
        case .poweredOff:
            print("未启动")
        case .poweredOn:
            print("可用")
            // 创建Service(服务)和Characteristics(特征)
            setupServiceAndCharacteristics()
            // 根据服务的UUID开始广播
            self.peripheralManager?.startAdvertising([CBAdvertisementDataServiceUUIDsKey : [CBUUID.init(string: Service_UUID)],CBAdvertisementDataLocalNameKey:UIDevice.current.name])
        }
    }
    
    func writeValue(dataStr:String) {
        let data = dataStr.data(using: .utf8)!
        if let charcter = characteristic {
            self.peripheralManager?.updateValue(data, for: charcter, onSubscribedCentrals: nil)
        }
    }
    
    /** 创建服务和特征
     注意swift中枚举的按位运算 '|' 要用[.read, .write, .notify]这种形式
     */
    private func setupServiceAndCharacteristics() {
        let serviceID = CBUUID.init(string: Service_UUID)
        let service = CBMutableService.init(type: serviceID, primary: true)
        let characteristicID = CBUUID.init(string: Characteristic_UUID)
        let characteristic = CBMutableCharacteristic.init(type: characteristicID,
                                                          properties: [.read, .write, .notify],
                                                          value: nil,
                                                          permissions: [.readable, .writeable])
        service.characteristics = [characteristic]
        self.peripheralManager?.add(service)
        self.characteristic = characteristic
    }
    
    /** 中心设备读取数据的时候回调 */
    func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
        // 请求中的数据,这里把文本框中的数据发给中心设备
        // 成功响应请求
        peripheral.respond(to: request, withResult: .success)
    }
    
    /** 中心设备写入数据 */
    func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
        let request = requests.first!
        // 成功响应请求
        peripheral.respond(to: request, withResult: .success)
        
        if let data = request.value {
            recieveCommandFormCenter(data: data)
        }
    }
    
    /** 订阅成功回调 */
    func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
        print("\(#function) 订阅成功回调")
    }
    
    /** 取消订阅回调 */
    func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) {
        print("\(#function) 取消订阅回调")
    }
    
    func recieveCommandFormCenter(data:Data) {
        let command:String = String.init(data: data, encoding: .utf8) ?? ""
    }
    
    //callBack
    func bleStateCallBackBlock(_ block: @escaping BLEStateBlock) {
        staseCallback = block
    }
  
}

相关文章

  • iOS蓝牙开发(三):App作为外设被连接的实现

    iOS蓝牙开发(三):App作为外设被连接的实现 iOS蓝牙开发(三):App作为外设被连接的实现

  • iOS - Bluetooth 蓝牙介绍(下)

    回去查看 iOS - Bluetooth 蓝牙介绍(上) 5、外设模式的使用 5.1 App 作为外设被连接的实现...

  • ios app作为蓝牙外设

  • iOS -- 蓝牙开发系列

    1、蓝牙相关的基础知识 2、蓝牙连接外设的代码实现 3、App作为外设被链接 4、BabyBluetooth蓝牙库介绍

  • ios设备app作为蓝牙外设端

    苹果手机可以作为蓝牙外设端,被蓝牙中央端来扫描连接交互数据,实现模拟蓝牙外设硬件。通过阅读CoreBluetoot...

  • iOS蓝牙开发

    iOS蓝牙开发有三个框架 蓝牙开发有两种模式:1.手机作为中心设备,获取外设的数据2.手机作为外设,对外提供数据(...

  • 蓝牙开发

    iOS蓝牙开发 Bluetooth蓝牙CoreBluetooth 蓝牙中心设备的实现 蓝牙外设的实现 有Demo ...

  • iOS蓝牙开发 Bluetooth蓝牙CoreBluetooth

    iOS蓝牙开发 Bluetooth蓝牙CoreBluetooth 蓝牙中心设备的实现 蓝牙外设的实现 有Demo ...

  • iOS CoreBluetooth

    iOS 蓝牙编程。 首先,本文讲述的是对等的端到端的通信,不涉及一些蓝牙外设等的硬件编程,但读懂了本文后,蓝牙外设...

  • CoreBluetooth

    iOS-BLE蓝牙开发持续更新 - 简书 蓝牙打印小票 一个第三方 IOS BLE4.0蓝牙和外设连接和收发数据的...

网友评论

      本文标题:ios app作为蓝牙外设

      本文链接:https://www.haomeiwen.com/subject/axcpnctx.html