由于最近的项目在做小程序蓝牙通讯这块的内容,所以将实现的过程在这简单的记录下。
1、首先要初始化蓝牙-检查蓝牙适配器是否打开
async initBluetooth(): Promise<void> {
return new Promise((resolve: any, reject: any) => {
const _this = this
if (BluetoothController.adapterOpend) {
console.log("蓝牙适配器已打开")
resolve(true)
return
}
wx.openBluetoothAdapter({
success(res) {
BluetoothController.adapterOpend = true
console.log("=====*****蓝牙适配器已打开")
resolve(true)
},
fail(error) { //用来判断蓝牙是否已打开
reject(error)
BluetoothController.adapterOpend = false
console.log("=====*****蓝牙适初始化失败", error)
}
})
})
}
//使用案例
initBluetooth().then()
2、开始搜寻附近的蓝牙外围设备
/**
* @param options
* options.keywords 蓝牙名称筛选关键字
* options.deviceid 可选参数,蓝牙设备id,连接用
*/
async searchAroundBLE(options: any): Promise<void> {
return new Promise((resolve: any, reject: any) => {
const _this = this
if (_this.startDiscovery) {
console.log("已开启蓝牙扫描,勿重复开启")
resolve(true)
return
}
_this.startDiscovery = true
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true,
services: options.services,
success(res) {
console.log('搜索成功', res);
resolve(true)
},
fail(error) {
reject(error)
_this.startDiscovery = false
},
})
})
}
//使用案例
searchAroundBLE({ 'keywords': [''], services: [] }).then()
3、监听搜索到的设备
/**
* @param options
* options.keywords 蓝牙名称筛选关键字
* options.deviceid 可选参数,蓝牙设备id,连接用
*/
async onBluetoothDeviceFound(options: any): Promise<void> {
return new Promise((resolve: any, reject: any) => {
let _this = this
let { keywords } = options
// 超时自动结束
_this.findTimer = setTimeout(() => {
clearTimeout(_this.findTimer)
if (!_this.connectStatus) {
reject({
success: false
})