微信小程序使用蓝牙连接设备流程
小程序使用蓝牙连接设备介绍 使用到的api
流程:
- 初始化蓝牙模块 wx.openBluetoothAdapter
wx.openBluetoothAdapter({
success: function (res) {
wx.showToast({
title: '初始化成功',
icon: 'success',
duration: 800
})
self.findMachine();
},
fail: function (res) {
wx.showToast({
title: '请开启蓝牙',
icon: 'error',
duration: 1500
})
}
})
- 搜索周边蓝牙设备 wx.startBluetoothDevicesDiscovery
findMachine() {
var that = this
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
interval: 0,
success: function (res) {
console.log(res)
wx.showLoading({
title: '正在搜索设备',
})
that.getMachine()
}
})
},
- 找到要连接的设备(根据名称查找) wx.getBluetoothDevices
getMachine() {
var that = this
wx.getBluetoothDevices({
success: function (res) {
console.log(res)
wx.hideLoading();
var list = res.devices;
if (list.length != 0) {
var name = "设备名称";
list.forEach(item => {
if (item.name == name || item.localName == name) {
that.connectMachine(item.deviceId);
}
});
}
},
fail: function () {
console.log("搜索蓝牙设备失败")
}
})
},
- 连接设备 wx.createBLEConnection
- 修改MTU(最大传输单元,看需求) wx.setBLEMTU
connectMachine(deviceId) {
var that = this;
wx.createBLEConnection({
deviceId: deviceId,
success: function (res) {
wx.showToast({
title: '连接成功',
icon: 'success',
duration: 800
})
wx.stopBluetoothDevicesDiscovery()
wx.getSystemInfoAsync({
success: (result) => {
console.log(result, '123')
var model = result.model;
if (model.indexOf('iPhone') == -1) {
const mtu = 500;
wx.setBLEMTU({
deviceId: deviceId,
mtu,
success: (res) => {
console.log(res)
console.log("setBLEMTU success>>", res)
if (res.errno == 0) {
that.getServiceId(deviceId)
}
},
fail: (res) => {
console.log(res, 123)
console.log("setBLEMTU fail>>", res)
}
})
}
else{
that.getServiceId(deviceId)
}
},
})
}
})
},
- 获取设备的uuid wx.getBLEDeviceServices
getServiceId(deviceId) {
var that = this
wx.getBLEDeviceServices({
deviceId: deviceId,
success: function (res) {
console.log(res)
var model = res.services[0]
var uuid = model.uuid;
that.getCharacteId(deviceId, uuid)
}
})
},
- 查询当前连接设备的特征值 wx.getBLEDeviceCharacteristics
- 指令写入到蓝牙设备当中 wx.writeBLECharacteristicValue
- 开启notify 功能 wx.notifyBLECharacteristicValueChange
- 监听功能 wx.onBLECharacteristicValueChange
getCharacteId(deviceId, uuid) {
var that = this;
wx.getBLEDeviceCharacteristics({
deviceId: deviceId,
serviceId: uuid,
success: function (res) {
console.log(res)
var list = res.characteristics;
if (list.length != 0) {
list.forEach(item => {
var model = item;
if (model.properties.write == true) {
var value = that.string2buffer('123');
wx.writeBLECharacteristicValue({
deviceId: deviceId,
serviceId: uuid,
characteristicId: model.uuid,
value: value,
success(res) {
console.log(res)
},
fail(res) {
console.log(res)
}
})
}
if (model.properties.read) {
wx.readBLECharacteristicValue({
deviceId: deviceId,
serviceId: uuid,
characteristicId: model.uuid,
success(res) {
console.log(res)
}
})
}
if (model.properties.notify || model.properties.indicate) {
wx.notifyBLECharacteristicValueChange(
deviceId: deviceId,
serviceId: uuid,
characteristicId: model.uuid,
state: true,
success(res) {
console.log(res);
wx.onBLECharacteristicValueChange((result) => {
console.log(result)
var value = that.ab2hex(result.value);
wx.closeBLEConnection({
deviceId,
})
wx.closeBluetoothAdapter()
})
},
fail(res) {
console.log(res)
}
})
}
});
}
}
})
},
流程用到的类型转换
将字符串转换成ArrayBufer
string2buffer(str) {
let val = ""
if (!str) return;
let length = str.length;
let index = 0;
let array = []
while (index < length) {
array.push(str.substring(index, index + 2));
index = index + 2;
}
val = array.join(",");
return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function (h) {
return parseInt(h, 16)
})).buffer
},
将ArrayBuffer转换成字符串
ab2hex(buffer) {
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
},
|