连接蓝牙设备总共需要一下几步
1.先查看系统蓝牙状态 uni.openBluetoothAdapter(obj)
2.搜索附近的蓝牙设备并且监听寻找到新设备的事件
uni.startBluetoothDevicesDiscovery(obj)搜索附近的蓝牙设备 uni.onBluetoothDeviceFound(obj)监听寻找到新设备的事件
3.成功找到对应蓝牙设备后 需关闭搜索
uni.stopBluetoothDevicesDiscovery(obj) 停止搜寻附近的蓝牙外围设备
4.连接低功耗蓝牙设备 连接成功后调用uni.getBLEDeviceServices来获取蓝牙设备所有服务
uni.createBLEConnection(obj) 连接低功耗蓝牙设备
uni.getBLEDeviceServices(obj) 获取蓝牙设备所有服务(service)。
5.获取蓝牙设备某个服务中所有特征值
1.先查看系统蓝牙状态
uni.openBluetoothAdapter(obj)
uni.openBluetoothAdapter({
success: function(res) {
console.log('是否开启蓝牙', res)
},
fail: function(msg) {
console.log(msg)
}
})
2.搜索附近的蓝牙设备 并且监听寻找到新设备的事件
let that = this
uni.startBluetoothDevicesDiscovery({
success: function(res) {
console.log('搜索设备---', res)
uni.onBluetoothDeviceFound(function(el) {
console.log('new device list has founded')
console.log(el)
console.log(that.ab2hex(el.devices[0].advertisData))
//找到对应蓝牙设备名字
if (el.devices[0].name == '云音乐ME01-1384') {
console.log("成功-------", el)
//成功后存储设备id
that.deviceId = el.devices[0].deviceId
that.stop()//关闭搜索 第三步方法名
}
})
},
})
3.成功找到对应蓝牙设备后 需关闭搜索附近设备
uni.stopBluetoothDevicesDiscovery({
success(res) {
console.log('停止搜索---', res)
}
})
4.连接低功耗蓝牙设备 连接成功后调用uni.getBLEDeviceServices来获取蓝牙设备所有服务
let that = this
uni.createBLEConnection({
deviceId: this.deviceId,
success: (res) => {
console.log('连接成功---', JSON.stringify(res))
//需延时连接,不然会报错
setTimeout(function() {
uni.getBLEDeviceServices({
deviceId: that.deviceId,
success: (res) => {
console.log('获取蓝牙设备所有服务', res)
that.uuid = res.services[0].uuid
that.huoqu(res.services[0].uuid) //第五步方法名
}
})
}, 1000)
}
})
5.获取蓝牙设备某个服务中所有特征值
let that = this
let deviceId = this.deviceId
uni.getBLEDeviceCharacteristics({
deviceId: this.deviceId,
serviceId: uuid,
success: (res) => {
that.characteristics = res.characteristics[0].uuid
console.log('获取--------', res)
},
fail: (res) => {
console.log('失败1--------', res)
}
})