小程序联调蓝牙与设备通讯
粗略的记录一下
- 初始化
wx.openBluetoothAdapter({
success: (res) => {
},
fail: (res) => {
}
})
2、搜索附近蓝牙设备
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,//是否允许重复上报同一设备。false 不允许, true 允许(设备多的情况下手机容易卡顿)
success: (res) => {
function ab2hex(buffer) {// ArrayBuffer转16进度字符串示例
var hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('');
}
//搜索到新设备回调
wx.onBluetoothDeviceFound((res) => {
var devices = res.devices;
})
},
fail:(res)=>{
}
})
- 停止搜索设备(找到设备后记得及时停止搜索设备)
wx.stopBluetoothDevicesDiscovery({
success: (res) => {
},
fail:(res)=>{
}
})
- 连接设备
- 4.1.1 连接蓝牙低功耗设备
wx.createBLEConnection({
deviceId,//设备deviceId
success: (res) => {
//支持低功耗就可以获取设备的serviceId
},
fail: (res) => {
reject(res)
}
})
- 4.1.2 获取蓝牙低功耗设备所有服务 (service)
wx.getBLEDeviceServices({
deviceId,
success: (res) => {
//得到serviceId
},
fail: (res) => {
}
})
- 4.1.3 获取蓝牙低功耗设备某个服务中所有特征 (characteristic)
wx.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res) => {
for (let i = 0; i < res.characteristics.length; i++) {
let item = res.characteristics[i]
if (item.properties.read) {//是否支持读
//读取蓝牙低功耗设备特征值的二进制数据。注意:必须设备的特征支持 read 才可以成功调用
wx.readBLECharacteristicValue({
deviceId,
serviceId,
characteristicId:item.uuid,
success(res) {
}
})
}
if (item.properties.notify || item.properties.indicate) {
/*启用蓝牙低功耗设备特征值变化时的 notify 功能 */
wx.notifyBLECharacteristicValueChange({
deviceId,
serviceId,
characteristicId:item.uuid,
state: true,
complete(res) {
}
})
}
}
},
fail(res) {
}
})
- 4.1.4 连接设备
wx.getConnectedBluetoothDevices({
services: [serviceId],//需要连接设备的serviceId(数组)
success (res) {
},
fail(error){
}
})
- 写入数据
//监听设备回复值
wx.onBLECharacteristicValueChange((characteristic) => {
//得到设备回复
})
let arr = [0x44,0x44,0x44]
wx.writeBLECharacteristicValue({
deviceId: this.deviceId,//已连接设备的deviceId
serviceId:serviceId,//已连接设备的serviceId(服务
characteristicId:charaId,//已连接设备的charaId(特征
value: new Uint8Array(arr).buffer,
success(res){
},
fail(res){
}
})
- 断开与蓝牙低功耗设备的连接
wx.closeBLEConnection({
deviceId: this.deviceId,
success: (res) => {
},
fail: (res) => {
}
})
- 关闭蓝牙模块
wx.closeBluetoothAdapter({
success: (res) => {
},
fail: (res) => {
}
})