// 微信小程序目前有蓝牙 API 共 18 个,其中操作蓝牙适配器的共有 4 个,分别是
// wx.openBluetoothAdapter 初始化蓝牙适配器
// wx.closeBluetoothAdapter 关闭蓝牙模块
// wx.getBluetoothAdapterState 获取本机蓝牙适配器状态
// wx.onBluetoothAdapterStateChange 监听蓝牙适配器状态变化事件
// 连接前使用的共有 4 个,分别是
// wx.startBluetoothDevicesDiscovery 开始搜寻附近的蓝牙外围设备
// wx.stopBluetoothDevicesDiscovery 停止搜寻附近的蓝牙外围设备
// wx.getBluetoothDevices 获取所有已发现的蓝牙设备
// wx.onBluetoothDeviceFound 监听寻找到新设备的事件
// 连接和断开时使用的共有 2 个,分别是
// wx.createBLEConnection 连接低功耗蓝牙设备
// wx.closeBLEConnection 断开与低功耗蓝牙设备的连接
// 连接成功后使用的共有 8 个,分别是
// wx.getConnectedBluetoothDevices 根据 uuid 获取处于已连接状态的设备
// wx.getBLEDeviceServices 获取蓝牙设备所有 service(服务)
// wx.getBLEDeviceCharacteristics 获取蓝牙设备所有 characteristic(特征值)
// wx.readBLECharacteristicValue 读取低功耗蓝牙设备的特征值的二进制数据值
// wx.writeBLECharacteristicValue 向低功耗蓝牙设备特征值中写入二进制数据
// wx.notifyBLECharacteristicValueChange 启用低功耗蓝牙设备特征值变化时的 notify 功能
// wx.onBLECharacteristicValueChange 监听低功耗蓝牙设备的特征值变化
// wx.onBLEConnectionStateChange 监听低功耗蓝牙连接的错误事件
const util = require('../../utils/util.js')
Page({
data: {
serviceCode: '0000FFE0', //筛选蓝牙查找区域
blueName: 'TouChuan', //判断蓝牙名称
blueValue: '',
connectMac: '', //蓝牙的deviceId
BluetoothDataList: [],
},
onLoad() {
this.openBluetoothAdapter();
},
//关闭蓝牙模块、释放蓝牙资源,保证连接顺畅
closeBluetoothAdapter() {
var that = this
wx.closeBluetoothAdapter({
complete() {
that.openBluetoothAdapter()
}
})
},
//初始化蓝牙
openBluetoothAdapter: function() {
var that = this;
// 蓝牙连接
wx.openBluetoothAdapter({
success: function(res) {
that.getBluetoothAdapterState();
},
fail: function(res) {
console.log(res);
wx.showModal({
title: '提示',
content: '请您打开蓝牙或检查微信是否授权蓝牙',
confirmColor: '#00b6b5',
showCancel: false,
success(res) {}
})
}
})
},
getBluetoothAdapterState: function() {
var that = this;
wx.getBluetoothAdapterState({
success: function(res) {
if (!res.discovering) {
that.startBluetoothDevicesDiscovery();
}
if (!res.available) {
wx.showModal({
title: '提示',
content: '当前蓝牙适配器不可用',
confirmColor: '#00b6b5',
showCancel: false,
success(res) {}
})
}
},
fail: function(res) {
wx.showModal({
title: '提示',
content: '适配蓝牙失败',
confirmColor: '#00b6b5',
showCancel: false,
success(res) {}
})
}
});
},
//搜索设备
startBluetoothDevicesDiscovery: function() {
var that = this;
wx.startBluetoothDevicesDiscovery({
// services: [that.data.serviceCode],
allowDuplicatesKey: false,
success: function(res) {
console.log('蓝牙获取列表成功');
// 第一种方法,需要给一点搜索时间
// setTimeout(() => {
// that.getBluetoothDevices();
// }, 1500)
//第二种方法
that.onBluetoothDeviceFound();
},
fail: function(res) {
wx.showModal({
title: '提示',
content: '搜索蓝牙设备失败'
})
}
})
},
// 获取所有已发现的设备
getBluetoothDevices: function() {
var that = this;
wx.getBluetoothDevices({
success(res) {
console.log(res)
var BluetoothDataList = that.data.BluetoothDataList; //数据列表,可以自己定义
res.devices.forEach(item => {
var buff = item.advertisData; //获取蓝牙的广播数据
var arrayBuff = Array.prototype.map.call(new Uint8Array(buff), x => (
'00' + x.toString(16)).slice(-2)).join(':');
arrayBuff = arrayBuff.toUpperCase() //将数据处理了获取macId
item.noteName = arrayBuff ? arrayBuff : item.deviceId; //将macId放进列表里面
BluetoothDataList.push(item);
})
that.setData({
BluetoothDataList: BluetoothDataList
})
}
})
},
// 获取所有已发现的设备
onBluetoothDeviceFound: function() {
var that = this;
wx.onBluetoothDeviceFound((res) => {
console.log(res)
var BluetoothDataList = this.data.BluetoothDataList; //数据列表,可以自己定义
res.devices.forEach(item => {
var buff = item.advertisData; //获取蓝牙的广播数据
var arrayBuff = Array.prototype.map.call(new Uint8Array(buff), x => ('00' +
x.toString(16)).slice(-2)).join(':');
arrayBuff = arrayBuff.toUpperCase() //将数据处理了获取macId
item.noteName = arrayBuff ? arrayBuff : item.deviceId; //将macId放进列表里面
if (item.name == that.data.blueName) {
that.stopBluetoothDevicesDiscovery();
//连接
that.connectTO(item);
}
BluetoothDataList.push(item);
})
that.setData({
BluetoothDataList: BluetoothDataList
})
})
},
//停止搜索周边设备
stopBluetoothDevicesDiscovery: function() {
wx.getBluetoothAdapterState({
success: function(res) {
if (res.discovering) {
wx.stopBluetoothDevicesDiscovery({
success: function(res) {
console.log("蓝牙停止搜索")
}
})
}
}
})
},
//连接设备
connectTO: function(mac, num = 0) {
var that = this;
return new Promise((reslove, rejcts) => {
wx.showLoading({
title: '连接中',
})
wx.createBLEConnection({
deviceId: mac.deviceId,
success: function(res) {
wx.hideLoading();
that.setData({
connectMac: mac.deviceId
})
reslove()
wx.onBLEConnectionStateChange(function(res) {
// 该方法回调中可以用于处理连接意外断开等异常情况
console.log(
`device ${res.deviceId} state has changed, connected: ${res.connected}`
)
if (!res.connected) {
that.connectTO(mac);
clearInterval(timer)
timer = null
} else {
console.log("蓝牙连接成功!")
that.getBLEDeviceServices(res.deviceId)
//监听取值
wx.onBLECharacteristicValueChange((res) => {
console.log(that.ab2hex(res.value))
that.setData({blueValue: that.ab2hex(res.value)
})
})
}
})
},
fail: function(res) {
wx.hideLoading()
if (num < 3) {
that.connectTO(mac, ++num);
} else {
wx.showModal({
title: '提示',
content: '蓝牙连接失败',
cancelText: '重新连接',
confirmText: '返回首页',
success(res) {
if (res.confirm) {
wx.switchTab({
url: '/pages/home/index',
})
}
if (res.cancel) {
that.connectTO(mac);
}
}
})
}
rejcts();
}
})
})
},
//获取蓝牙设备所有服务(service)。
getBLEDeviceServices(deviceId) {
var that = this
console.log("进入服务");
setTimeout(() => {
wx.getBLEDeviceServices({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: deviceId,
success: (res) => {
console.log('device services:', res)
res.services.forEach((item) => {
console.log('serviceId:', item.uuid)
that.getBLEDeviceCharacteristics(deviceId, item.uuid)
})
}
})
}, 1000)
},
// 获取蓝牙特征值
getBLEDeviceCharacteristics(deviceId, serviceId) {
var that = this
console.log("进入特征");
setTimeout(() => {
wx.getBLEDeviceCharacteristics({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId: serviceId,
success: (res) => {
console.log(res)
res.characteristics.forEach((item) => {
console.log('characteristicId:', item.uuid)
that.notifyBLECharacteristicValueChange(deviceId, serviceId,
item.uuid)
})
},
fail: (res) => {
console.log(res)
}
})
}, 2000)
},
// 启用 notify 功能
notifyBLECharacteristicValueChange(deviceId, serviceId, characteristicId) {
var that = this
wx.notifyBLECharacteristicValueChange({
state: true, // 启用 notify 功能
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId: serviceId,
// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId: characteristicId,
success: (res) => {
console.log('notifyBLECharacteristicValueChange success', res.errMsg)
that.readBLECharacteristicValue(deviceId, serviceId, characteristicId);
},
fail: (res) => {
console.log('notifyBLECharacteristicValueChange fail', res.errMsg)
}
})
},
// 读取设备二进制数据
readBLECharacteristicValue(deviceId, serviceId, characteristicId) {
console.log('进入读取');
wx.readBLECharacteristicValue({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId: serviceId,
// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId: characteristicId,
success: (res) => {
console.log('readBLECharacteristicValue success:', res)
},
fail: (res) => {
console.log('readBLECharacteristicValue fail:', res)
}
})
},
ab2hex(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
},
})