小程序与蓝牙设备通讯,总结一下分为下面几点:
1.小程序初始化蓝牙模块
2.搜索设备
3.连接设备 获取蓝牙的所有服务以及服务对应的特征值,根据特征值进行读写和监听设备的数据返回
4. 写入数据
5. 读取蓝牙设备返回数据
下面我们看具体的实现步骤
初始化蓝牙模块
//初始化蓝牙
openBluetoothAdapter() {
var that = this;
//初始化蓝牙模块
wx.openBluetoothAdapter({
success: (res) => {
console.log('openBluetoothAdapter success', res)
that.startBluetoothDevicesDiscovery()
},
fail: (res) => {
console.log(res);
if (res.errCode === 10001) {
wx.onBluetoothAdapterStateChange(function (res) {
console.log('onBluetoothAdapterStateChange', res)
if (res.available) {
that.startBluetoothDevicesDiscovery()
}
})
}
}
})
},
搜索蓝牙设备
//开始搜寻附近的蓝牙外围设备
startBluetoothDevicesDiscovery() {
var that = this;
if (that._discoveryStarted) {
return
}
that._discoveryStarted = true
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true,
success: (res) => {
console.log('startBluetoothDevicesDiscovery success', res)
that.onBluetoothDeviceFound()
},
})
},
//停止搜寻附近的蓝牙外围设备
stopBluetoothDevicesDiscovery() {
wx.stopBluetoothDevicesDiscovery()
},
//监听寻找到新设备的事件
onBluetoothDeviceFound() {
var that = this;
wx.onBluetoothDeviceFound((res) => {
res.devices.forEach(device => {
console.log(device);
if (!device.name && !device.localName) {
return
}
const foundDevices = that.data.devices
const idx = inArray(foundDevices, 'deviceId', device.deviceId)
const data = {
}
if (idx === -1) {
data[`devices[${
foundDevices.length

本文详细介绍小程序与蓝牙设备通讯的步骤,包括蓝牙模块初始化、设备搜索、连接、读写及监听数据返回。涵盖分包写入、数据组包及错误处理等关键环节。

1514

被折叠的 条评论
为什么被折叠?



