微信小程序的低功耗蓝牙
- 流程图
- 开关检测与初始化
- 定位服务检测
- 蓝牙状态判定
- 蓝牙扫描
- 蓝牙连接与断开相关流程
- 数据发送
流程图
微信小程序蓝牙使用跟手机App差不多。
小程序与蓝牙设备建立连接进行通讯的一般流程如下:
设备 周围环境 小程序 蓝牙广播 扫描蓝牙对象 获取蓝牙广播包列表 发起蓝牙连接 蓝牙状态回调 获取服务列表进行校验 获取特征进行校验 使能通知类特征 数据读写操作 数据返回与通知 设备 周围环境 小程序
这将产生一个流程图。:
1.蓝牙广播
1.蓝牙扫描
2.扫描回调
3.发起连接流程
4.连接结果返回
是
否
蓝牙设备
周边环境
小程序
5.是否连接成功
6.与设备进行数据通讯操作
1.重新扫描
开关检测与初始化
定位服务检测
因为安卓系统使用蓝牙需要定位权限以及打开定位服务,所以使用蓝牙前最好先进行定位权限与开关检测
getUserLocation: function () {
let that = this;
wx.getSystemInfo({
success:function(res) {
if(res.system.indexOf('Android')==0){//判断是安卓系统(安卓系统需要定位权限才能使用蓝牙)
if(!wx.getSystemInfoSync().locationAuthorized){//判断是否有定位权限
wx.authorize({//请求定位权限
scope:'scope.userLocation',
success(res){
// console.log("定位授权成功:"+res.errMsg)
that.checkGPS()
},
fail(res){
// console.log("定位授权失败:"+res.errMsg)
wx.showToast({
content:'定位授权失败!'
})
wx.navigateBack()
}
})
}else{
that.checkGPS()
}
}
}
})
},
checkGPS:function (){//判断系统定位服务是否打开
if(!wx.getSystemInfoSync().locationEnabled){
wx.showModal({
title: '请打开定位服务',
content: '为确保蓝牙功能正常使用请打开定位服务',
confirmText: '确认',
showCancel: false
})
}
}
蓝牙状态判定
判断该手机是否支持低功耗蓝牙,以及蓝牙开关是否打开
bleInit:function(){
wx.openBluetoothAdapter({
success: (res) => {
//成功之后
},
fail: (res) => {
console.log('openBluetoothAdapter fail', res)
if (res.errCode === 10001) {
wx.showModal({
title: '',
content: '请先打开蓝牙开关',
})
}else if(res.errCode === 10009){
wx.showModal({
title: '',
content: '当前手机不支持蓝牙操作',
})
}else{
wx.showModal({
title: '',
content: res.errMsg,
})
}
that.setData({
connect_progress:0,
})
}
})
}
蓝牙扫描
启用蓝牙扫描以及监听扫描回调:
startBluetoothDevicesDiscovery() {
//启动蓝牙扫描
if (this._discoveryStarted) {
return
}
this._discoveryStarted = true
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true,
success: (res) => {
//console.log('startBluetoothDevicesDiscovery success', res)
this.onBluetoothDeviceFound()
},
})
},
stopBluetoothDevicesDiscovery() {
//停止蓝牙散买
var that = this;
this._discoveryStarted = false
wx.stopBluetoothDevicesDiscovery()
},
onBluetoothDeviceFound() {
wx.onBluetoothDeviceFound((res) => {
res.devices.forEach(device => {
if (!device.name && !device.localName) {
return
}
//console.log(device)
//蓝牙广播包数据拆解
const ad = ab2hex(device.advertisData)
const buffer = device.advertisData;
const gbb = ab2hex(buffer).split(' ');
//TODO: 从蓝牙广播获得数据后进行相关处理
//刷新前界面显示的设备列表
const foundDevices = this.data.devices
if(foundDevices.length==0){
var that = this
setTimeout(function(e){
that.stopBluetoothDevicesDiscovery()
that.queryDeviceBindState()
},3000)
}
//遍历寻找同ID设备的序号
const idx = inArray(foundDevices, 'deviceId', device.deviceId)
const data = {}
//不改变原排序的情况下更新设备信息
if (idx === -1) {
data[`devices[${foundDevices.length}]`] = device
} else {
data[`devices[${idx}]`] = device
}
//赋值通知更新
this.setData(data)
})
})
},
蓝牙连接与断开相关流程
根据蓝牙对象建立连接:
connect(ds){
wx.showLoading({
title: '连接中...',
})
this.getBleStateChange()//监听蓝牙状态变化
this.stopBluetoothDevicesDiscovery()//停止扫描
this.connectDeviceId = ds.deviceId;
this.deviceState.database_id = ds.database_id;
const deviceId = ds.deviceId
wx.createBLEConnection({
deviceId,
success: (res) => {
//TODO:蓝牙连接成功后的操作
},
fail:err=>{
//失败后的重连接逻辑
this.connect_count+=1;
if(this.connect_count<5){
this.connect(ds)
}else{
wx.hideLoading()
this.connect_count = 0;
}
},
complete:(re)=>{
console.log(re)
}
})
},
getBleStateChange(){
//蓝牙状态监听
wx.onBLEConnectionStateChange(res => {
console.log("connectChange", res)
if(res.connected){
this.getBLEDeviceServices(this.data.connectDeviceId)
}else{
//重连逻辑
if(typeof(this.data..connectDeviceId)!="undefined"&&this.data.connectDeviceId!=''){
var ds = {
this.connectDeviceId,
this.deviceState.database_id
};
this.connect(ds)
}
}
if (!res.connected){
wx.hideLoading()
}
})
}
,
getBLEDeviceServices(deviceId) {
//获取服务列表进行校验
wx.getBLEDeviceServices({
deviceId,
success: (res) => {
//console.log('Services', res.services)
for (let i = 0; i < res.services.length; i++) {
//console.log('getthisuuid', res.services[i].uuid)
if (res.services[i].uuid=="XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX") {
this.deviceId = deviceId
this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
return
}
}
}
})
},
getBLEDeviceCharacteristics(deviceId, serviceId) {
//蓝牙特征码获取与校验
wx.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res) => {
//console.log('getBLEDeviceCharacteristics success', res.characteristics)
for (let i = 0; i < res.characteristics.length; i++) {
let item = res.characteristics[i]
// if (item.properties.read) {
// //接口读取到的信息需要在 onBLECharacteristicValueChange 方法注册的回调中获取
// wx.readBLECharacteristicValue({
// deviceId,
// serviceId,
// characteristicId: item.uuid,
// })
// }
if (item.properties.write) {
this.setData({
canWrite: true
})
this._deviceId = deviceId
this._serviceId = serviceId
this._characteristicId = item.uuid
}
if (item.properties.notify || item.properties.indicate) {
//通知类特征使能
wx.notifyBLECharacteristicValueChange({
deviceId,
serviceId,
characteristicId: item.uuid,
state: true,
})
}
}
this.sendCheckSum()
},
fail(res) {
console.error('getBLEDeviceCharacteristics', res)
}
})
// 设备通知数据回调监听
wx.onBLECharacteristicValueChange((characteristic) => {
if (characteristic.characteristicId == "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"){
this.checkUpload(new Uint8Array(characteristic.value))
}
})
},
数据发送
蓝牙数据发送:
sendData() {
let bindbuffer = new ArrayBuffer(1)
let dataView = new DataView(bindbuffer)
dataView.setUint8(0, 0x01)
wx.writeBLECharacteristicValue({
deviceId: this._deviceId,
serviceId: this._serviceId,
characteristicId: this._characteristicId,
value: bindbuffer,
success: (res) => {
console.log('writeBLECharacteristicValue', res)
},
fail: (err) => {
console.error('writeBLECharacteristicValue', err)
}
})
},
微信小程序的一般蓝牙操作流程就这样了。