当前位置: 首页 > 科技观察

OpenHarmony经典蓝牙配对详情_0

时间:2023-03-12 13:30:08 科技观察

了解更多开源内容请访问:51CTO开源基础软件社区https://ost.51cto.com一、使用介绍设备中的蓝牙功能需要扫描设备首先,然后配对并连接扫描的设备。蓝牙配对就像两个蓝牙设备之间的注册。配对类似于两个设备交换电话号码或其他信息以确保相互确认信息。并且在设备首次配对后,设备已经保存了必要的信息,因此无需重复配对过程即可轻松再次连接。在OpenHarmony设备中,进入蓝牙设置并勾选蓝牙开关后,会进行一次蓝牙扫描,我们可以点击扫描到的设备进行配对请求。2.配对请求流程(1)应用端请求配对点击扫描到的设备请求配对。应用端代码如下(代码路径:applications\standard\settings\product\phone\src\main\ets\MainAbility\pages\bluetooth.ets):...if(this.availableDevices&&this.availableDevices.length>=1){List(){//配对设备列表ForEach(this.availableDevices,(item:BluetoothDevice)=>{ListItem(){Row(){EntryComponent({settingIcon:getDeviceIconPath(item.deviceType),settingTitle:item.deviceName?item.deviceName:item.deviceId,settingSummary:getConnectionStateText(item),settingValue:'',settingArrow:'',settingArrowStyle:'',settingUri:'',image_wh:$r('app.float.wh_value_24'),height:getConnectionStateText(item)==''?$r('app.float.wh_value_56'):($r('app.float.wh_value_64')),fontSize:($r('app.float.font_16')),});.width(ConfigData.WH_100_100).borderRadius($r("app.float.radius_24")).padding($r('app.float.distance_4')).backgroundColor($r("app.color.white_bg_color"))//点击当前设备请求配对.onClick(()=>{LogUtil.info(this.TAG_PAGE+'itemonclick:'+JSON.stringify(item));this.pairDevice(item)})}},item=>JSON.stringify(item));}.backgroundColor($r("app.color.white_bg_color")).borderRadius($r("app.float.radius_24")).divider({strokeWidth:1,color:$r('app.color.color_E3E3E3_grey'),startMargin:$r('app.float.wh_value_52'),endMargin:$r('app.float.wh_value_12')})}else{...点击事件在onClick函数中处理,通过调用this.pairDevice(item)向选中的设备发起配对请求pairDevice(item)函数接口如下:/***Pairdevice*@paramdevice*/@LogpairDevice(device:BluetoothDevice){this.controller.pair(device.deviceId,(pinCode:string)=>{LogUtil.info(this.TAG_PAGE+'pairDevicesuccesscallback:pinCode='+pinCode);//显示配对密码对话框this.pairPinCode=pinCodethis.pairingDevice=device;this.pairDialog.open();},()=>{LogUtil.info(this.TAG_PAGE+'pairDeviceerrorcallback');this.showPairFailedDialog()})}接口请求配对,继续调用this.controller.pair()方法,如下(代码路径:applications\standard\settings\product\phone\src\main\ets\MainAbility\controller\bluetooth\BluetoothDeviceController.ts):/***配对设备。**@paramdeviceId设备id*@paramsuccess成功回调*@paramerror错误回调*/pair(deviceId:string,success?:(pinCode:string)=>void,error?:()=>void):void{常量设备:BluetoothDevice=this.getAvailable设备(设备编号);if(device&&device.connectionState===DeviceState.STATE_PAIRING){LogUtil.log(this.TAG+`bluetoothnoAavailabledeviceordevice(${deviceId})isalreadypairing.`)return;}//开始监听pinCodeBluetoothModel.subscribePinRequired((pinRequiredParam:{deviceId:string;pinCode:string;})=>{LogUtil.log(this.TAG+'bluetoothsubscribePinRequiredcallback.pinRequiredParam='+JSON.stringify(pinRequiredParam));this.pairPinCode=pinRequiredParam.pinCode;BluetoothModel.unsubscribePinRequired(()=>LogUtil.log(this.TAG+'availablepinRequiredunsubscribed.'));if(success){success(this.pairPinCode);}})//开始配对constresult=BluetoothModel.pairDevice(deviceId);LogUtil.log(this.TAG+'bluetoothpairDeviceresult='+result);if(!result){BluetoothModel.unsubscribePinRequired(()=>LogUtil.log(this.TAG+'availablepinRequiredunsubscribed.'));如果(错误){错误();从代码可以看出,它首先监听扫描设备的配对pin码并获取其设备地址,然后通过BluetoothModel.pairDevice(deviceId)方法传入设备地址进行配对请求.pairDevice方法最终是通过调用NAPI的pairDevice(deviceId)接口来实现的。/***配对设备*/pairDevice(deviceId:string):boolean{returnbluetooth.pairDevice(deviceId);}(2)NAPI端到C++端的配对请求流程NAPI端到C++端的主要流程如下图所示:主要流程分为三个阶段:napi_bluetooth_host.cpp的NAPI端接口,调用接口通过IPC的蓝牙SA。从服务器到适配器的调用。适配器对栈的调用最终调用栈中蓝牙驱动外设子系统的接口。3.配对响应过程(1)C++到NAPI端的配对响应过程配对成功后的响应过程如下图所示:这个过程反向对应请求阶段的三个过程,从协议栈到适配器,然后是NAPI端观察员。(2)应用设置端的响应监控界面。应用设置端监听配对成功的主要代码如下:/***Subscribebond状态变化*/privatesubscribeBondStateChange(){BluetoothModel.subscribeBondStateChange((data:{deviceId:string;bondState:number;})=>{LogUtil.log(this.TAG+'bluetoothsubscribeBondStateChangecallback.');//配对设备if(data.bondState!==BondState.BOND_STATE_BONDING){this.refreshPairedDevices();}//可用设备if(data.bondState==BondState.BOND_STATE_BONDING){//casebonding//什么也不做,仍然在监听//案例失败this.getAvailableDevice(data.deviceId).connectionState=DeviceState.STATE_DISCONNECTED;this.forceRefresh(this.availableDevices);AppStorage.SetOrCreate('bluetoothAvailableDevices',this.availa蓝牙设备);this.showConnectFailedDialog();}elseif(data.bondState==BondState.BOND_STATE_BONDED){//案例成功LogUtil.log(this.TAG+'bluetoothbonded:removedevice.');this.removeAvailableDevice(数据.deviceId);BluetoothModel.connectDevice(data.deviceId);}});}subscribeBondStateChange函数用于监控配对状态。配对成功后,会调用BluetoothModel.connectDevice(data.deviceId)接口链接配置文件。4.应用端配对日志流程设置应用从配对请求到配对成功响应的主要日志如下://Requestpairing08-0509:11:29.75316831692D03b00/JSApp:appLog:SettingsBluetoothDeviceControllerbluetoothpairDeviceresult=true//配对状态为pairing08-0509:11:29.75416831692I03b00/JSApp:appLog:SettingsBluetoothModelsubscribeBondStateChange->bondStateChangedata:{"deviceId":"18:95:52:80:E2:3E","state":1}//配对密码08-0509:11:30.45116831692I03b00/JSApp:appLog:SettingsBluetoothModelsubscribePinRequired->pinRequiredreturn:{"deviceId":"18:95:52:80:E2:3E","pinCode":897679}//密码对话框08-0509:11:30.47216831692D03b00/JSApp:appLog:SettingsbluetoothPairDialogaboutToAppearpinCode=897679//配对状态08-0509:11:30.87016831692I03b00/JSApp:appLog:SettingsBluetoothModelsubscribeBondStateC更多开源信息请访问:51CTO开源基础软件社区https://ost.51cto.com。