引用此js文件就行了
// 使用方式
import bluetooth from './bluetooth.js';
// 使用设备名称匹配蓝牙设备
bluetooth.name = 'xxxx';
wx.showLoading({
title: '开门中...',
mask : true,
});
await bluetooth.openBluetoothAdapter();
蓝牙设备匹配具体实现
/* eslint-disable no-underscore-dangle */
function inArray(arr, key, val) {
for (let i = 0; i < arr.length; i++) {
if (arr[i][key] === val) {
return i;
}
}
return -1;
}
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {
return ('00' + bit.toString(16)).slice(-2);
});
return hexArr.join('');
}
/**
* hex转ArrayBuffer
*/
function stringToBuffer(arr) {
var length = arr.length;
var buffer = new ArrayBuffer(length);
var dataview = new DataView(buffer);
for (let i = 0; i < length; i++) {
dataview.setUint8(i, '0x' + arr[i]);
// dataview.setUint8(i, arr[i].charAt(i).charCodeAt())
}
return buffer;
}
const bluetooth = {
// 引用bluetooth时,获取后台传入的设备名称或者id
name : '',
bluetoothDeviceId: '',
// 1.初始化蓝牙模块。iOS 上开启主机/从机模式时需分别调用一次,指定对应的 mode:
// central主机模式
// peripheral从机模式
async openBluetoothAdapter() {
try {
await wx.openBluetoothAdapter();
this.startBluetoothDevicesDiscovery();
} catch (error) {
if (error.errCode === 10001) {
wx.showToast({
title : '请打开蓝牙再次尝试开门',
icon : 'none',
duration: 1500,
});
wx.onBluetoothAdapterStateChange((res) => {
if (res.available) {
this.startBluetoothDevicesDiscovery();
}
});
}
}
},
getBluetoothAdapterState() {
wx.getBluetoothAdapterState({
success: (res) => {
if (res.discovering) {
this.onBluetoothDeviceFound();
} else if (res.available) {
this.startBluetoothDevicesDiscovery();
}
},
});
},
// 开始搜寻附近的蓝牙外围设备。
// 2.此操作比较耗费系统资源,请在搜索并连接到设备后调用 wx.stopBluetoothDevicesDiscovery 方法停止搜索。
async startBluetoothDevicesDiscovery() {
if (this._discoveryStarted) {
return;
}
this._discoveryStarted = true;
await wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
// 要搜索的蓝牙设备主 service 的 uuid 列表。某些蓝牙设备会广播自己的主 service 的 uuid。如果设置此参数,则只搜索广播包有对应uuid 的主服务的蓝牙设备。建议主要通过该参数过滤掉周边不需要处理的其他蓝牙设备。
services : ['XXXX'],
});
this.onBluetoothDeviceFound();
},
// 停止搜寻附近的蓝牙外围设备。
// 5.若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。
stopBluetoothDevicesDiscovery() {
wx.stopBluetoothDevicesDiscovery();
},
// 3.监听寻找到新设备的事件
onBluetoothDeviceFound() {
wx.onBluetoothDeviceFound((res) => {
res.devices.forEach((device) => {
// 设备匹配
// 以蓝牙设备服务 uuid进行匹配
// if (device.advertisServiceUUIDs.some(uuid => uuid === '000018F0-0000-1000-8000-00805F9B34FB')) {
// this.createBLEConnection(device.deviceId, device.name);
// }
// 以蓝牙设备 名称进行匹配
if (device.name === this.name) {
this.createBLEConnection(device.deviceId, device.name);
}
// 以蓝牙设备id进行匹配(此id在安卓系统为mac地址唯一不变,每台iOS设备获取的设备id都不同,可以让设备厂家暴露设备mac给iOS设备进行匹配)
// if (device.deviceId === this.bluetoothDeviceId) {
// this.createBLEConnection(device.deviceId, device.name);
// }
});
});
// 计时器
this.timer = setTimeout(async() => {
await wx.hideLoading();
wx.showToast({
title : '开门超时请重试',
icon : 'none',
duration: 1500,
});
this.closeBluetoothAdapter();
}, 10 * 1000);
},
// 连接低功耗蓝牙设备。
// 4.
createBLEConnection(deviceId, name) {
wx.createBLEConnection({
deviceId,
success: (res) => {
this.getBLEDeviceServices(deviceId);
},
});
this.stopBluetoothDevicesDiscovery();
},
closeBLEConnection() {
wx.closeBLEConnection({
deviceId: this._deviceId,
});
},
// 6.获取蓝牙设备所有服务(service)。
getBLEDeviceServices(deviceId) {
wx.getBLEDeviceServices({
deviceId,
success: (res) => {
for (let i = 0; i < res.services.length; i++) {
// 匹配设备厂家说明书所给的相应服务uuid
if (res.services[i].uuid.includes('XXXX')) {
this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
return;
}
}
},
});
},
// 获取蓝牙设备某个服务中所有特征值(characteristic)
// 7.
getBLEDeviceCharacteristics(deviceId, serviceId) {
wx.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res) => {
for (let i = 0; i < res.characteristics.length; i++) {
let item = res.characteristics[i];
if (item.properties.read) {
wx.readBLECharacteristicValue({
deviceId,
serviceId,
characteristicId: item.uuid,
});
}
// 匹配设备厂家说明书上相应的可写入服务
if (item.uuid.includes('XXXX')) {
this._deviceId = deviceId;
this._serviceId = serviceId;
this._characteristicId = item.uuid;
this.writeBLECharacteristicValue();
}
// if (item.properties.notify || item.properties.indicate) {
// wx.notifyBLECharacteristicValueChange({
// deviceId,
// serviceId,
// characteristicId: item.uuid,
// state : true,
// });
// }
}
},
fail(res) {
console.error('getBLEDeviceCharacteristics', res);
},
});
// 操作之前先监听,保证第一时间获取数据
// wx.onBLECharacteristicValueChange((characteristic) => {
// const idx = inArray(
// this.data.chs,
// 'uuid',
// characteristic.characteristicId,
// )
// const data = {}
// if (idx === -1) {
// data[`chs[${this.data.chs.length}]`] = {
// uuid: characteristic.characteristicId,
// value: ab2hex(characteristic.value),
// }
// } else {
// data[`chs[${idx}]`] = {
// uuid: characteristic.characteristicId,
// value: ab2hex(characteristic.value),
// }
// }
// data[`chs[${this.data.chs.length}]`] = {
// uuid: characteristic.characteristicId,
// value: ab2hex(characteristic.value)
// }
// this.setData(data)
// })
},
// 向低功耗蓝牙设备特征值中写入二进制数据。
// 注意:必须设备的特征值支持 write 才可以成功调用。
// 8
async writeBLECharacteristicValue() {
// 蓝牙写入指令
// 此为示例
const arr = ['fe', '12','88','55','11'];
const buffer = stringToBuffer(arr);
try {
await wx.writeBLECharacteristicValue({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId : this._deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId : this._serviceId,
// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId: this._characteristicId,
value : buffer,
});
// 关闭之前调用的 showLoading
await wx.hideLoading();
wx.showToast({
title: '开门成功',
icon : 'none',
});
// 开门成功清除定时器;
clearTimeout(this.timer);
} catch (error) {
console.log(`error`, error);
wx.showToast({
title: '开门失败请重试',
icon : 'none',
});
}
this.closeBluetoothAdapter();
},
closeBluetoothAdapter() {
wx.closeBluetoothAdapter();
this._discoveryStarted = false;
},
};
export default bluetooth;