小程序 蓝牙功能
- 1.授予蓝牙权限
- 2.蓝牙初始化
- 3.监听寻找新设备
- 4.搜索新设备
- 5.建立连接⭐⭐⭐⭐⭐⭐⭐
- 6.监听蓝牙低功耗连接状态改变事件
- 8.监听特征值变化
- 9.发送数据
1.授予蓝牙权限
const authBlue = (callback, initApp) => {
app = initApp;
wx.getSetting().then(res => {
if (!res.authSetting['scope.bluetooth']) {
return wx.authorize({
scope: 'scope.bluetooth',
})
} else {
if (callback != null) {
callback({
blueAuth: true
})
}
return new Promise(() => {})
}
}).then(() => {
if (callback != null) {
callback({
blueAuth: true
})
}
return new Promise(() => {})
}).catch(err => {
if (callback != null)
callback({
blueAuth: false
})
console.err(err);
})
}
2.蓝牙初始化
const init = (onFound) => {
console.log("2.蓝牙初始化");
wx.openBluetoothAdapter({
mode: 'central'
}).then(res => {
app.globalData.isOpenBleAdapter = true
wx.onBluetoothAdapterStateChange((res) => {
if (!res.available) {
wx.showModal({
title: '温馨提示',
content: '蓝牙蓝牙适配器不可用,请重新启动',
showCancel: false
})
}
})
onFound();
}).catch(() => {
wx.showToast({
title: '请检查手机蓝牙是否打开',
icon: 'none',
})
})
}
3.监听寻找新设备
const onDeviceFound = (addDevicesList) => {
console.log("3.监听寻找新设备");
wx.onBluetoothDeviceFound((res) => {
const devicesList = []
for (const item of res.devices) {
if (!item.connectable) continue;
let device = Device.filterDevices(item)
if (device && addDevicesList != null) {
var existingObjIndex = devicesList.findIndex(function (obj) {
return obj.deviceId === device.deviceId;
});
if (existingObjIndex !== -1) {
Object.assign(devicesList[existingObjIndex], device);
} else {
devicesList.push(device);
}
}
}
addDevicesList(devicesList)
})
}
4.搜索新设备
const startDevicesDiscovery = (obj) => {
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true,
interval: 1000,
success: (res) => {
console.log("4.搜索新设备");
},
fail: function (res) {
wx.showToast({
title: '搜索蓝牙外围设备失败,请重新初始化蓝牙!',
icon: 'none',
})
}
})
}
5.建立连接⭐⭐⭐⭐⭐⭐⭐
const createConnect = (deviceId, func) => {
let mtu = 209
let serviceId = '0000FFE0-0000-1000-8000-00805F9B34FB';
let characteristics;
wx.createBLEConnection({
deviceId
}).then((res) => {
if (res.errCode === 0 || res.errCode === -1) {
console.log('1.连接成功');
const systemInfo = wx.getSystemInfoSync();
const platform = systemInfo.platform;
if (platform === 'android') {
return wx.setBLEMTU({
deviceId,
mtu
});
} else if (platform === 'ios') {
return {
mtu
}
} else {
return {
mtu
}
}
} else {
console.log('连接失败');
func({
isConnect: false
})
return new Promise(() => {})
}
}, error => {
console.log(error)
func({ isConnect: false})
return new Promise(() => {})
}).then((res) => {
console.log("2.MTU设置成功,协商MTU:", res.mtu, deviceId, serviceId);
return wx.getBLEDeviceServices({deviceId});
}, (res) => {
console.log("2.MTU设置失败:", res);
func({ isConnect: false})
return new Promise(() => {})
}).then((res) => {
console.log("3.获取蓝牙服务成功", res);
for (let i = 0; i < res.services.length; i++) {
console.log("+++++++++发现服务:", res.services[i].uuid);
if (res.services[i].uuid === '0000FFE0-0000-1000-8000-00805F9B34FB') {
return wx.getBLEDeviceCharacteristics({
deviceId,
serviceId
});
}
}
},(err) => {
console.error("3.获取蓝牙服务失败", err);
func({ isConnect: false})
return new Promise(() => {})
}).then((res) => {
console.log("4.获取UUIDS成功", res);
characteristics = res.characteristics
for (let i = 0; i < characteristics.length; i++) {
const item = characteristics[i];
if (item.properties.notify || item.properties.indicate) {
return wx.notifyBLECharacteristicValueChange({
deviceId: deviceId,
serviceId: serviceId,
characteristicId: item.uuid,
state: true
});
}
}
}, (res) => {
console.log("4.获取UUIDS失败", res);
func({ isConnect: false})
return new Promise(() => {})
}).then((res) => {
console.log('5.订阅特征变化成功', res);
for (let i = 0; i < characteristics.length; i++) {
let item = characteristics[i];
if (item.uuid.substr(0, 8) == '0000FFE1') {
app.globalData.characteristicId = item.uuid
break;
}
}
func({ isConnect: true})
}, (err) => {
console.log("5.订阅特征变化失败", res);
func({ isConnect: false})
return new Promise(() => {})
}).catch((err) => {
func({ isConnect: false})
console.error(err);
});
}
6.监听蓝牙低功耗连接状态改变事件
const onConnectionStateChange = (listenBleStatus) => {
wx.onBLEConnectionStateChange(res => listenBleStatus(res))
}
8.监听特征值变化
const onCharacteristicValueChange = (onBleValueChange) => {
wx.onBLECharacteristicValueChange(res => onBleValueChange(res))
}
function onBleValueChange(res) {
console.log("监听到数据", res);
.
.
.
}
9.发送数据
const writeCharacteristicValue = (deviceId, command) => {
return wx.writeBLECharacteristicValue({
characteristicId: app.globalData.characteristicId,
deviceId: deviceId,
serviceId: app.globalData.serviceId,
value: command,
})
}