小程序低功耗蓝牙控制设备
小程序控制蓝牙的过程&api
- 初始化蓝牙适配器wx.openBluetoothAdapter()
- 获取本机蓝牙链接状态wx.getBluetoothAdapterState()
- 开启搜索蓝牙wx.startBluetoothDevicesDiscovery()
- 获取所有蓝牙列表wx.getBluetoothDevices()
- 根据蓝牙列表匹配自己需要的广播蓝牙(厂商会给自己的设备规则),获取广播数据
- 把上一步匹配的到的蓝牙设备,进行连接wx.createBLEConnection()
- 连接成功,停止搜索wx.stopBluetoothDevicesDiscovery()
- 连接成功后,需要获取设备的uuid,设备特征值,发送指令需要用到wx.getBLEDeviceServices()
- 获取设备的characteristicId,发送指令需要用到wx.getBLEDeviceCharacteristics
- 发送密钥(密钥是从厂商获取到的)指令给门锁 wx.writeBLECharacteristicValue()
1. 初始化蓝牙适配器
initBluetoothAdapert function()(
const that = this
console.log("初始化蓝牙适配器");
wx.openBluetoothAdapter({
success: function (res) {
console.log("1.1获取自身蓝牙状态");
that.getBluetoothAdapterState();
},
fail: function (err) {
console.log(err);
wx.showToast({
title: '请检查您的蓝牙是否开启',
icon: 'success',
duration: 2000
})
setTimeout(function () {
wx.hideToast()
}, 2000)
}
});
)
2.获取蓝牙适配器状态
getBluetoothAdapterState() {
console.log('2.获取本机蓝牙连接状态')
const that = this
wx.getBluetoothAdapterState({
success: function (res) {
console.log("2.1获取本地蓝牙状态 available=true表示蓝牙已开启")
console.log(res)
if (res.available) {
that.startBluetoothDevicesDiscovery()
} else {
wx.showToast({
title: '请打开您的蓝牙后重新尝试',
icon: 'success',
duration: 2000
})
}
},
fail: function(res