最近公司想做一个小程序使用蓝牙连接硬件设备进行相互传输数据指令, 接下来是我做这个功能的总结
两种蓝牙普遍使用规格
- 蓝牙基础率/增强数据率
也称为经典蓝牙
。常用在对数据传输带宽有一定要求的场景上,比如需要传输音频数据的蓝牙音箱、蓝牙耳
机等; - 蓝牙低功耗
特点就是功耗极低,传输速度更快
, 常用在对续航要求较高且只需小数据量传输的各种智能电子产品中,比如
智能穿戴设备、智能家电、传感器等,应用场景广泛。
实现步骤
![](https://img.haomeiwen.com/i18133846/8c2e32014bf6ce54.jpg)
初始化蓝牙
/**
* 初始化蓝牙设备
*/
onConnect() {
let that = this;
wx.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口
success: function(res) {
that.startBluetoothDevicesDiscovery(); // 调用搜索
wx.showLoading({
title: '搜索中',
})
},
fail: function(res) {
wx.showToast({
title: '请先开启蓝牙',
icon: 'none',
duration: 1000
})
}
});
},
开始搜索蓝牙设备
startBluetoothDevicesDiscovery: function() {
var that = this;
wx.startBluetoothDevicesDiscovery({
success: function(res) {
console.log("discovery", res);
if (res.errCode == 0) { // 搜索成功
that.getConnect(); // 调用连接该设备
}
},
});
},
开始连接
getConnect: function() {
var that = this;
var timer = setInterval(function() {
wx.getBluetoothDevices({ // 获取在蓝牙模块生效期间所有搜索到的蓝牙设备。包括已经和本机处于连接状态的设备
success: function(res) {
console.log("devices", res);
for (var i = 0; i < res.devices.length; i++) {
if (res.devices[i].name == that.data.deviceName) {
wx.hideLoading();
wx.showLoading({
title: '连接中',
})
that.setData({
isFinded: true
});
clearInterval(timer);
that.setData({
deviceId: res.devices[i].deviceId
});
console.log('设备号', that.data.deviceId);
console.log("开始尝试建立连接");
wx.createBLEConnection({ // 连接蓝牙低功耗设备。
deviceId: that.data.deviceId,
timeout: 10000,
success: function(res) {
console.log(res);
if (res.errCode == 0) {
console.log('连接成功')
that.setData({
isConnected: true
});
wx.stopBluetoothDevicesDiscovery(); // 如果已经找到, 停止搜寻附近的蓝牙外围设备。
} else {
wx.showModal({
title: '提示',
content: '不能正常对蓝牙设备进行连接',
showCancel: false
})
}
},
fail: (res) => {
wx.hideLoading();
if (res.errCode == 10012) {
wx.showModal({
title: '提示',
content: '连接超时',
showCancel: false
})
}
console.warn("fail", res);
},
complete: () => {
wx.hideLoading();
}
})
break;
}
}
}
});
},
3000);
setTimeout(function() {
if (!that.data.isFinded && !that.data.isConnected) {
clearInterval(timer);
that.setData({
isFailed: false
});
wx.hideLoading();
wx.showModal({
title: '提示',
content: '搜索蓝牙超时',
showCancel: false
})
}
}, 12000);
},
获取设备信息
onGetuuid(){
let that = this;
if(that.data.isConnected && that.data.isFailed){
wx.showLoading({
title: '获取serviceId',
})
console.log("开始获取设备信息");
wx.getBLEDeviceServices({
deviceId,
success(getServicesRes) {
console.log("getServicesRes", getServicesRes);
let service = getServicesRes.services[1]
let serviceId = service.uuid
console.log(serviceId);
wx.showLoading({
title: '获取characteristicId',
})
wx.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success(getCharactersRes) {
console.log("getCharactersRes", getCharactersRes);
wx.hideLoading();
let characteristic = getCharactersRes.characteristics[0]
let characteristicId = characteristic.uuid
wx.notifyBLECharacteristicValueChange({
state: true,
deviceId,
serviceId,
characteristicI,
success() {
console.log('开始监听特征值')
wx.onBLECharacteristicValueChange(function (onNotityChangeRes) {
console.log('监听到特征值更新', onNotityChangeRes);
let characteristicValue = that.ab2hex(onNotityChangeRes.value);
console.log("characteristicValue-16进制", characteristicValue ); // 设备返回的16进制值
wx.showModal({
title: '监听到特征值更新',
content: `更新后的特征值(16进制格式):${characteristicValue}`,
showCancel: false
})
})
},
fail: (res) => {
console.warn("监听特征值失败");
}
})
},
fail: (res) => {
console.warn("获取特征值信息失败", res);
},
complete: (res) => {
console.log('获取服务信息完成',res);
wx.hideLoading();
}
})
},
fail: (res) => {
console.warn("获取服务信息失败", res);
},
complete: () => {
wx.hideLoading();
}
})
}else{
wx.showToast({
title: '请先连接蓝牙',
})
}
},
发送指令
onSendCommand() {
var buf = new ArrayBuffer(6);
let dataView = new DataView(buf);
wx.writeBLECharacteristicValue({
// 需要上面的 getBluetoothDevices 或者 onBluetoothDeviceFound 接口中获取
deviceId,
// 需要在上面的 getBLEDeviceServices 接口中获取
serviceId,
// getBLEDeviceCharacteristics 接口中获取
characteristicId,
value: buf,
success: function(res) {
console.log(res);
console.log("发送指令成功");
wx.showToast({
title: '发送成功',
icon: 'none'
})
},
fail: function(res) {
console.warn("发送指令失败", res)
}
})
},
断开连接
onCloseConnect(){
this.setData({
isConnected:false,
isFinded:false
})
wx.closeBLEConnection({
deviceId: this.data.deviceId,
success: function(res) {
console.log("成功断开连接");
wx.showToast({
title: '成功断开连接',
})
},
})
}
网友评论