当前位置:   article > 正文

Uni-App开发BLE低功耗蓝牙流程_uniapp ble

uniapp ble

Uni-App开发BLE低功耗蓝牙步骤

示例文件已上传gitee:https://gitee.com/yan_rookie/uniapp_bluetooth.git
如果对你有记得点个赞哦!

注:微信小程序同样适用,只需吧前缀uni.修改为wx.

最全总结,看此一篇就够!!!!

开发蓝牙很多小伙伴刚开始一头雾水,不知道从何下手,网上可以查的资料少之又少,所以写这篇文章来总结一下BLE低功耗蓝牙开发流程,话不多说,仔细看!!

  1. 初始化蓝牙 uni.openBluetoothAdapter(OBJECT)
  2. 开始搜索蓝牙设备 uni.startBluetoothDevicesDiscovery(OBJECT)
  3. 发现外围设备 uni.onBluetoothDeviceFound(CALLBACK)
  4. 停止搜寻附近的蓝牙外围设备 uni.stopBluetoothDevicesDiscovery(OBJECT)
  5. 连接低功耗蓝牙设备 uni.createBLEConnection(OBJECT)
  6. 获取蓝牙设备所有服务 uni.getBLEDeviceServices(OBJECT)
  7. 获取蓝牙特征 uni.getBLEDeviceCharacteristics(OBJECT)
  8. 启用蓝牙设备特征值变化时的 notify 功能 uni.notifyBLECharacteristicValueChange(OBJECT)
  9. 监听低功耗蓝牙设备的特征值变化 uni.onBLECharacteristicValueChange(CALLBACK)
  10. 写入蓝牙 uni.writeBLECharacteristicValue(OBJECT)

基本使用步骤我们总结完了,那么接下来就介绍怎么使用

1.初始化蓝牙
这里主要目的就是检测一下手机蓝牙是否打开

uni.openBluetoothAdapter({
   
	success:(res)=> {
    //已打开
		uni.getBluetoothAdapterState({
   //蓝牙的匹配状态
			success:(res1)=>{
   
			console.log(res1,'“本机设备的蓝牙已打开”')	
			// 开始搜索蓝牙设备
			this.startBluetoothDeviceDiscovery()
			},
			fail(error) {
   
				uni.showToast({
   icon:'none',title: '查看手机蓝牙是否打开'	
			}
		});
		
	},
	fail:err=>{
    //未打开 
		uni.showToast({
   icon:'none',title: '查看手机蓝牙是否打开'});
	}
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

2.开始搜索蓝牙设备

// 开始搜索蓝牙设备
startBluetoothDeviceDiscovery(){
   
	uni.startBluetoothDevicesDiscovery({
   
		success: (res) => {
   
			console.log('startBluetoothDevicesDiscovery success', res)
			// 发现外围设备
			this.onBluetoothDeviceFound()
		},fail:err=>{
   
			console.log(err,'错误信息')
		}
	})
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

3.发现外围设备
到这个位置就会搜索到设备了
这个地方重点就是获取到了 deviceId 这是连接蓝牙的重要ID,存起来到data里面后面我们会用到

// 发现外围设备
onBluetoothDeviceFound() {
   
	// console.log("zhixing")
	uni.onBluetoothDeviceFound((res) => {
   
		// console.log(res)
		// ["name", "deviceId"]
		
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/573636
推荐阅读
相关标签
  

闽ICP备14008679号