草庐IT

CoreBluetooth系列教程(二):蓝牙常用API

卢叁 2023-03-28 原文

上篇讲了蓝牙相关的基本概念,现在结合代码讲讲具体实现。首先需要创建一个CBCentralManager对象,检查蓝牙的状态,只有蓝牙为poweredOn状态,才可进行下一步连接动作。

CBCentralManager初始化

先导入`CoreBluetooth` 框架
 var centralManager: CBCentralManager!
    //设置deleagte、queue、可选参数options,options可以为nil,也可设置CBCentralManagerOptionShowPowerAlertKey蓝牙提醒弹窗和CBCentralManagerOptionRestoreIdentifierKey字符串(一个唯一的标识符,用来恢复蓝牙连接的,在后台的长连接中可能用到)
    override init() {
        super.init()
        
        self.centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    
    init(stateRestoreIdentifier: String) {
        super.init()
        
        self.centralManager = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionRestoreIdentifierKey: stateRestoreIdentifier])
    }

主要API的使用

  // 获取已连接的设备
    open func retrieveConnectedPeripherals(withServices serviceUUIDs: [CBUUID]) -> [CBPeripheral]
  // 扫描设备(serviceUUIDs:需要扫描的设备serviceUUID数组,设置为nil,则扫描附近所有蓝牙设备,通常为了提高效率,填入特定的serviceUUID数组)
   open func scanForPeripherals(withServices serviceUUIDs: [CBUUID]?, options: [String : Any]? = nil)
  // 停止扫描
    open func stopScan()
  // 连接设备
    open func connect(_ peripheral: CBPeripheral, options: [String : Any]? = nil)
 // 断开连接
    open func cancelPeripheralConnection(_ peripheral: CBPeripheral)

CBCentralManagerDelegate的回调

基本所有的回调都在Delegate方法里处理

// 蓝牙状态变更
 func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state.rawValue {
        case 0: // .unknown
            
        case 1: // .resetting
            
        case 2: // .unsupported
            
        case 3: // .unauthorized
            
        case 4: // .poweredOff(蓝牙关闭)
            
        case 5: // .poweredOn(蓝牙打开)
            
        default:
            fatalError("Unsupported BLE CentralState")
        }
    }

// 扫描到设备  advertisementData:广播包数据 RSSI:信号强度
  func centralManager(_ central: CBCentralManager,
                        didDiscover peripheral: CBPeripheral,
                        advertisementData: [String: Any],
                        rssi RSSI: NSNumber) {
        
    }
// 设备成功连接
 func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
       
    }

// 设备连接失败
optional func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?)  {

}
// 设备连接断开
 func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {

}

与设备连接成功后,会生成一个CBPeripheral对象,用来操作设备数据的读写和监听等。

CBPeripheral的使用

public enum CBPeripheralState : Int, @unchecked Sendable {

    
    case disconnected = 0 // 连接断开

    case connecting = 1 // 正在连接中

    case connected = 2 // 已连接

    @available(watchOS 2.0, *)
    case disconnecting = 3 //断开连接中
}
// 设备写入服务类型,注意要根据设备读取的特征值来写入,否则写入报错。
public enum CBCharacteristicWriteType : Int, @unchecked Sendable {

    
    case withResponse = 0

    case withoutResponse = 1
}
open class CBPeripheral : CBPeer {
  // 蓝牙名称
    open var name: String? { get }
 // 信号强度
    open var rssi: NSNumber? { get }
// 连接状态
    open var state: CBPeripheralState { get }
// 扫描到的设备服务
    open var services: [CBService]? { get }
// 写入方式是withResponse还是withoutResponse
    open var canSendWriteWithoutResponse: Bool { get }
// 连接成功,检索当前连接的信号强度,回调方法:peripheral:didReadRSSI:error:
    open func readRSSI()
// 扫描设备可用的服务,serviceUUIDs 需要扫描的设备的服务的id,如果为nil,则扫描所有的服务,回调方法:peripheral:didDiscoverServices:
    open func discoverServices(_ serviceUUIDs: [CBUUID]?)
// includedServiceUUIDs  需要发现的服务service中的服务id列表,如果为nil,则扫描服务内所有的服务,较慢,不推荐使用。回调方法:peripheral:didDiscoverIncludedServicesForService:error:
    open func discoverIncludedServices(_ includedServiceUUIDs: [CBUUID]?, for service: CBService) 
//  characteristicUUIDs  数组,内含需要被发现的所有特征值类型,如果为nil,则为所有特征值。回调方法为:peripheral:didDiscoverCharacteristicsForService:error:
    open func discoverCharacteristics(_ characteristicUUIDs: [CBUUID]?, for service: CBService)
// characteristic   需要读取的服务特征值,回调方法:  peripheral:didUpdateValueForCharacteristic:error:
    open func readValue(for characteristic: CBCharacteristic)
// 获取向一个写服务可发送的最大字节数
    open func maximumWriteValueLength(for type: CBCharacteristicWriteType) -> Int
//   data:需要写入的数据 characteristic:写服务特征  type: 写服务的 类型(有/无响应),需要注意的是,传入的type是根据characteristic!.properties.rawValue & CBCharacteristicProperties.writeWithoutResponse.rawValue 来决定,否则随意传入type会导致写入失败。
    open func writeValue(_ data: Data, for characteristic: CBCharacteristic, type: CBCharacteristicWriteType)
// 根据characteristic的properties来设置,若为true,说明只要有数据更新就会回调新数据。
    open func setNotifyValue(_ enabled: Bool, for characteristic: CBCharacteristic)
}

CBPeripheralDelegate的回调

// 设备名称更新
optional func peripheralDidUpdateName(_ peripheral: CBPeripheral) {

}
// peripheral :需要更新的设备 invalidatedServices:失效的服务
    optional func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {

}
// peripheral :需要更新的设备 error:出现错误的原因。readRSSI的回调方法。
    optional func peripheralDidUpdateRSSI(_ peripheral: CBPeripheral, error: Error?) {

}
// peripheral :需要更新的设备 RSSI:设备的RSSI。readRSSI的回调方法
    optional func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) {

}
// peripheral:扫描到的设备  error :错误原因。discoverServices的回调方法。
    optional func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {

}
// peripheral:当前设备 service : 设备服务  error:错误原因。 discoverIncludedServices:forService的回调
    optional func peripheral(_ peripheral: CBPeripheral, didDiscoverIncludedServicesFor service: CBService, error: Error?) {

}
// peripheral:当前设备 service: 设备服务 error:错误原因。discoverCharacteristics:forService的回调
    optional func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

}
//  peripheral:当前设备 characteristic:设备特征 error:错误原因。当前设备特征值有更新就回调。
    optional func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

}
// peripheral:当前设备 characteristic:设备特征 error:错误原因。writeValue:forCharacteristic:type的回调
    optional func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {

}
// peripheral:当前设备 characteristic:设备特征 error:错误原因。setNotifyValue:forCharacteristic的回调。
    optional func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {

}

一个设备有多个service,每个service都有多个characteristic,一层层找下来找到我们需要操作的characteristic,然后按硬件的要求进行读写和监听等操作。

有关CoreBluetooth系列教程(二):蓝牙常用API的更多相关文章

  1. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  2. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  3. ruby-on-rails - 使用一系列等级计算字母等级 - 2

    这里是Ruby新手。完成一些练习后碰壁了。练习:计算一系列成绩的字母等级创建一个方法get_grade来接受测试分数数组。数组中的每个分数应介于0和100之间,其中100是最大分数。计算平均分并将字母等级作为字符串返回,即“A”、“B”、“C”、“D”、“E”或“F”。我一直返回错误:avg.rb:1:syntaxerror,unexpectedtLBRACK,expecting')'defget_grade([100,90,80])^avg.rb:1:syntaxerror,unexpected')',expecting$end这是我目前所拥有的。我想坚持使用下面的方法或.join,

  4. ruby-on-rails - ActionController::RoutingError: 未初始化常量 Api::V1::ApiController - 2

    我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc

  5. 【鸿蒙应用开发系列】- 获取系统设备信息以及版本API兼容调用方式 - 2

    在应用开发中,有时候我们需要获取系统的设备信息,用于数据上报和行为分析。那在鸿蒙系统中,我们应该怎么去获取设备的系统信息呢,比如说获取手机的系统版本号、手机的制造商、手机型号等数据。1、获取方式这里分为两种情况,一种是设备信息的获取,一种是系统信息的获取。1.1、获取设备信息获取设备信息,鸿蒙的SDK包为我们提供了DeviceInfo类,通过该类的一些静态方法,可以获取设备信息,DeviceInfo类的包路径为:ohos.system.DeviceInfo.具体的方法如下:ModifierandTypeMethodDescriptionstatic StringgetAbiList​()Obt

  6. ruby-on-rails - Mandrill API 模板 - 2

    我正在使用Mandrill的RubyAPIGem并使用以下简单的测试模板:testastic按照Heroku指南中的示例,我有以下Ruby代码:require'mandrill'm=Mandrill::API.newrendered=m.templates.render'test-template',[{:header=>'someheadertext',:main_section=>'Themaincontentblock',:footer=>'asdf'}]mail(:to=>"JaysonLane",:subject=>"TestEmail")do|format|format.h

  7. postman接口测试工具-基础使用教程 - 2

    1.postman介绍Postman一款非常流行的API调试工具。其实,开发人员用的更多。因为测试人员做接口测试会有更多选择,例如Jmeter、soapUI等。不过,对于开发过程中去调试接口,Postman确实足够的简单方便,而且功能强大。2.下载安装官网地址:https://www.postman.com/下载完成后双击安装吧,安装过程极其简单,无需任何操作3.使用教程这里以百度为例,工具使用简单,填写URL地址即可发送请求,在下方查看响应结果和响应状态码常用方法都有支持请求方法:getpostputdeleteGet、Post、Put与Delete的作用get:请求方法一般是用于数据查询,

  8. 在VMware16虚拟机安装Ubuntu详细教程 - 2

    在VMware16.2.4安装Ubuntu一、安装VMware1.打开VMwareWorkstationPro官网,点击即可进入。2.进入后向下滑动找到Workstation16ProforWindows,点击立即下载。3.下载完成,文件大小615MB,如下图:4.鼠标右击,以管理员身份运行。5.点击下一步6.勾选条款,点击下一步7.先勾选,再点击下一步8.去掉勾选,点击下一步9.点击下一步10.点击安装11.点击许可证12.在百度上搜索VM16许可证,复制填入,然后点击输入即可,亲测有效。13.点击完成14.重启系统,点击是15.双击VMwareWorkstationPro图标,进入虚拟机主

  9. 阿里云RDS——产品系列概述 - 2

    基础版云数据库RDS的产品系列包括基础版、高可用版、集群版、三节点企业版,本文介绍基础版实例的相关信息。RDS基础版实例也称为单机版实例,只有单个数据库节点,计算与存储分离,性价比超高。说明RDS基础版实例只有一个数据库节点,没有备节点作为热备份,因此当该节点意外宕机或者执行重启实例、变更配置、版本升级等任务时,会出现较长时间的不可用。如果业务对数据库的可用性要求较高,不建议使用基础版实例,可选择其他系列(如高可用版),部分基础版实例也支持升级为高可用版。基础版与高可用版的对比拓扑图如下所示。优势 性能由于不提供备节点,主节点不会因为实时的数据库复制而产生额外的性能开销,因此基础版的性能相对于

  10. ruby-on-rails - 在 Ruby (on Rails) 中使用 imgur API 获取图像 - 2

    我正在尝试使用Ruby2.0.0和Rails4.0.0提供的API从imgur中提取图像。我已尝试按照Ruby2.0.0文档中列出的各种方式构建http请求,但均无济于事。代码如下:require'net/http'require'net/https'defimgurheaders={"Authorization"=>"Client-ID"+my_client_id}path="/3/gallery/image/#{img_id}.json"uri=URI("https://api.imgur.com"+path)request,data=Net::HTTP::Get.new(path

随机推荐