微信小程序之蓝牙通信

微信小程序之蓝牙通信

纯手工打造,通过本篇的学习,就可以快速上手微信小程序蓝牙相关的开发。

一、蓝牙通信流程

1.打开蓝牙适配器
	// 先关闭蓝牙适配器
	wx.closeBluetoothAdapter({
        success: (res) => {
        },
      })
      
    // 打开适配器
    wx.openBluetoothAdapter({
        mode: 'central', // ios必须要带这个参数
        success: (res) => {
          // adapter建立成功,可以通过观察者模式告诉页面
          
          // 开启适配器状态的监听
          wx.onBluetoothAdapterStateChange((result) => 		   {
            if (!result.available) { // 适配器不可用,可能用户关闭了手机的蓝牙
            }
          })         
        },
        fail (err) { // 蓝牙适配器未开启
          if (err.errCode === BLUETOOTH_NOT_OPEN) {
          	// 手机蓝牙未开启
          } else {
			// 可能未授权小程序蓝牙权限
          }
        }
      })

注意:打开蓝牙适配器需要授权小程序蓝牙权限

2.查找蓝牙设备
// 开启设备查找的监听
wx.onBluetoothDeviceFound((result) => {
	const device = result.devices; // 返回的设备列表
	// 可以根据自己的需求处理,查找设备,包括设备的自定义数据。
	// 查找到设备后,进行连接操作。
});

// 查找设备
wx.startBluetoothDevicesDiscovery({
          allowDuplicatesKey: false,
          powerLevel: 'high',
          services: [SERVICE_UUID], // 通过服务的UUID过滤不相关的设备
          // interval: 1000
          success: (res) => {
            
          },
          fail: (err) => { // 1.未授权微信定位服务;2.太频繁调用这个方法
            
            if (err.errMsg && err.errMsg.indexOf('frequently') != -1) {
              // 搜索设备太频繁
            } else {
              mObservers.forEach(item => {
                item(12) // 未授权微信定位服务
              })
            }            
          }
        })

注意:Android或者鸿蒙手机,需要微信已经使用过定位服务,并且定位服务已经授权给微信,定位服务已开启。

3.连接蓝牙设备
wx.createBLEConnection({
              deviceId: deviceId,
              success (res) {
              	  // 开启连接状态的监听
              	  
                  // 获取可用的服务
                 
              },
              fail (res) {

                  // 连接失败, 关闭适配器
              }
            })

注意:如果需要输入匹配码,设备端的匹配数量满时,有新设备需要接入时,连接会失败。

4.查找ServiceUUID
wx.getBLEDeviceServices({
              deviceId: deviceId,
              success (res) {                
				// 全部的服务UUID
                let services = res.services
                // 根据需要的服务UUID,获取蓝牙特征值
              },
              fail (res) {
              }
            })
5.操作特征值
 wx.getBLEDeviceCharacteristics({
          deviceId: deviceId,
          serviceId: serviceUuid,
          success (res) {
			// 当前服务UUID下的特征值列表
            let characteristics = res.characteristics;
			
			// 开启监听数据接收的特征值        
          },
          fail (res) {
            // 断开连接,关闭适配器
          }
        })
6.设置监听数据的特征值
wx.notifyBLECharacteristicValueChange({
        characteristicId: characteristicNofityUuid,
        deviceId: deviceId,
        serviceId: serviceUuid,
        state: true,
        success: (res) => {
		  // 开启数据接收的监听器
          
        },
        fail: (res) => { 
          // ios有可能取消匹配,也会调用这里
        }
      })

二、向蓝牙设备写数据

wx.writeBLECharacteristicValue({
          characteristicId: characteristicWriteUuid,
          deviceId: deviceId,
          serviceId: serviceUUID,
          value: data,
          success, // 回调函数
          fail, // 回调函数
          complete (result) {

          },
          writeType: 'writeNoResponse' // 防止ios写数据时报错
        })

三、接收数据

wx.onBLECharacteristicValueChange((result) => {

            let value = result.value;
            // 通过观察者模式通知需要使用到数据的地方
           
        })

四、判断小程序是否授权蓝牙

通过获取权限列表进行处理

wx.getSetting({
      success: (res) => {
        let authSetting = res.authSetting;

        if (authSetting['scope.bluetooth'] == false) { // 说明用户拒绝了使用蓝牙的权限
          // 到设置页面
          wx.openSetting({
            fail: (error) => {
            }
          })
        } else { // 从未去连接过蓝牙或者已同意使用蓝牙
        }
      },
      fail: (error) => {
        wx.showToast({
          title: '获取授权列表失败!',
        })
      }
    })  

如需转载请注明原地址

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jjr_1984

谢谢您的鼓励!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值