uni-app蓝牙开锁篇

uni-app蓝牙开锁篇

uni-app的api和微信的api其实很相似,用法一样,在这里奉上我之前在项目中实现蓝牙开锁的代码,我会说明每一步的步骤,哪个步骤用哪个api,每个api的详细用法可以去uni-app官网参考文档

蓝牙整个步骤:

  1. 初始化蓝牙
  2. 开始搜寻附近的蓝牙外围设备
  3. 监听寻找到新设备的事件
  4. 搜寻到需要的蓝牙,停止搜寻附近的蓝牙外围设备
  5. 连接低功耗蓝牙设备
  6. 获取蓝牙设备所有服务(service)
  7. 获取蓝牙设备某个服务中所有特征值(characteristic)
  8. 启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值。注意:必须设备的特征值支持 notify 或者 indicate 才可以成功调用
  9. 向低功耗蓝牙设备特征值中写入二进制数据。
uni.openBluetoothAdapter({//首先初始化蓝牙  
    success(res) {  
        console.log(JSON.stringify(res))  
        uni.startBluetoothDevicesDiscovery({//这里是开启蓝牙搜寻  
            success: (res) => {  
                console.log('startBluetoothDevicesDiscovery success', res)  
                uni.onBluetoothDeviceFound((res) => {//这一步是监听返回的蓝牙设备  
                    console.log(JSON.stringify(res))  
                    res.devices.forEach(device => {//这一步就是去筛选找到的蓝牙中,有没有你匹配的名称  
                        console.log(JSON.stringify(device))  
                        if (device.name == 'XiaoanTech') {  
                            this.DeviceID = device.deviceId  
                            let DeviceID = device.deviceId//这里是拿到的uuid  
                            uni.stopBluetoothDevicesDiscovery({//当找到匹配的蓝牙后就关掉蓝牙搜寻,因为蓝牙搜寻很耗性能  
                                success(res) {  
                                    console.log(JSON.stringify(res))  
                                }  
                            })  
                            console.log(DeviceID)  
                            uni.createBLEConnection({//连接低功耗蓝牙设备  
                                deviceId:DeviceID,//传入刚刚获取的uuid  
                                success(res) {  
                                    console.log(JSON.stringify(res))  
                                    setTimeout(function(){//这里为什么要用setTimeout呢,等等下面会解释  
                                        uni.getBLEDeviceServices({//获取蓝牙设备所有服务  
                                            deviceId:DeviceID,  
                                            success(res) {  
                                                console.log(JSON.stringify(res))  
                                                uni.getBLEDeviceCharacteristics({//获取蓝牙设备某个服务中所有特征值  
                                                    deviceId:DeviceID,  
                                                    serviceId:this.ServiceUUID,  
                                                    success(res) {  
                                                        console.log(JSON.stringify(res))  
                                                        uni.notifyBLECharacteristicValueChange({  
                                                            state: true, // 启用 notify 功能  
                                                            deviceId:DeviceID,  
                                                            serviceId:this.ServiceUUID,  
                                                            characteristicId:self.characteristicId,  
                                                            success(res) {  
                                                                console.log('notifyBLECharacteristicValueChange success', res.errMsg)  
                                                                uni.showToast({  
                                                                    title: '开启蓝牙连接',  
                                                                    duration: 2000  
                                                                });  
                                                            },  
                                                            fail(res) {  
                                                                console.log(JSON.stringify(res))  
                                                            }  
                                                        })  
                                                    },  
                                                    fail(res){  
                                                        console.log(JSON.stringify(res))   
                                                    }  
                                                })  
                                            },  
                                            fail(res){  
                                                console.log(JSON.stringify(res))   
                                            }  
                                        })  
                                    }, 1000)  
                                },  
                                fail(res) {  
                                    console.log(res)  
                                    if (res.errCode == 10001) {  
                                        uni.showToast({  
                                            title: '蓝牙未打开',  
                                            duration: 2000,  
                                        })  
                                    } else {  
                                        uni.showToast({  
                                            title: res.errMsg,  
                                            duration: 2000,  
                                        })  
                                    }  
                                }  
                            })  
                        }  
                    })  
                })  
            }  
        })  
    },  
    fail(res) {  
        console.log(res)  
    }  
})

发送指令:

SendChange: function () {//开锁  
    var self = this  

    // 向蓝牙设备发送一个0x00的16进制数据  
    let buffer = new ArrayBuffer(8)  
    let dataView = new DataView(buffer)  
    dataView.setUint8(0, 0x20)//开锁指令  
    dataView.setUint8(1, 0x05)//字节  
    dataView.setUint8(2, 0x0A)//指令  
    dataView.setUint8(3, 0x0A)//指令  
    dataView.setUint8(4, 0x05)//指令  
    dataView.setUint8(5, 0x05)//指令  
    dataView.setUint8(6, 0x00)//指令  
    dataView.setUint8(7, 0x43)  
    uni.writeBLECharacteristicValue({  
        deviceId:self.DeviceID,  
        serviceId:self.ServiceUUID,  
        characteristicId:self.characteristicId,  
        value: buffer,  
        success(res) {  
            console.log('writeBLECharacteristicValue success', res.errMsg)  
            uni.showToast({  
                title: '开锁',  
                duration: 2000  
            });  
        },  
        fail(res) {  
            console.log(JSON.stringify(res))  
            console.log(JSON.stringify(buffer))  
        }  
    })  
},  
CloseChange: function () {//关锁  
    var self = this  

    // 向蓝牙设备发送一个0x00的16进制数据  
    let buffer = new ArrayBuffer(8)  
    let dataView = new DataView(buffer)  
    dataView.setUint8(0, 0x20)  
    dataView.setUint8(1, 0x05)  
    dataView.setUint8(2, 0x0A)  
    dataView.setUint8(3, 0x0A)  
    dataView.setUint8(4, 0x05)  
    dataView.setUint8(5, 0x05)  
    dataView.setUint8(6, 0x01)  
    dataView.setUint8(7, 0x44)  
    uni.writeBLECharacteristicValue({  
        deviceId:self.DeviceID,  
        serviceId:self.ServiceUUID,  
        characteristicId:self.characteristicId,  
        value: buffer,  
        success(res) {  
            console.log('writeBLECharacteristicValue success', res.errMsg)  
            uni.showToast({  
                title: '关锁',  
                duration: 2000  
            });  
        },  
        fail(res) {  
            console.log(JSON.stringify(res))  
            console.log(JSON.stringify(buffer))  
        }  
    })  
}

文章有缺陷,因为蓝牙的指令文档被我搞不见了,只能通过理解写给大家看,希望能帮到大家,谢谢


更多关于uni-app蓝牙开锁篇的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于uni-app蓝牙开锁篇的实战教程也可以访问 https://www.itying.com/category-93-b0.html


uni-app中实现蓝牙开锁功能,通常需要结合蓝牙API与设备的蓝牙锁进行通信。以下是一个简化的代码示例,展示如何在uni-app中使用蓝牙API进行设备扫描、连接以及发送开锁指令。

1. 初始化蓝牙适配器

在应用启动时,需要初始化蓝牙适配器并监听蓝牙状态变化。

// main.js 或者在应用的某个生命周期函数中
uni.openBluetoothAdapter({
  success: function (res) {
    console.log('蓝牙适配器初始化成功', res)
  },
  fail: function (err) {
    console.error('蓝牙适配器初始化失败', err)
  }
})

uni.onBluetoothAdapterStateChange(function (res) {
  console.log('蓝牙适配器状态变化', res)
  if (!res.available) {
    uni.showToast({
      title: '蓝牙不可用',
      icon: 'none'
    })
  }
})

2. 扫描蓝牙设备

扫描周围的蓝牙设备,找到需要连接的蓝牙锁。

function startBluetoothDevicesDiscovery() {
  uni.startBluetoothDevicesDiscovery({
    allowDuplicatesKey: false,
    success: function (res) {
      console.log('开始扫描蓝牙设备', res)
      uni.onBluetoothDeviceFound(function (device) {
        // 假设蓝牙锁的设备名称为 'LockDevice'
        if (device.name === 'LockDevice') {
          console.log('找到蓝牙锁设备', device)
          stopBluetoothDevicesDiscovery()
          connectToBluetoothDevice(device.deviceId)
        }
      })
    },
    fail: function (err) {
      console.error('扫描蓝牙设备失败', err)
    }
  })
}

function stopBluetoothDevicesDiscovery() {
  uni.stopBluetoothDevicesDiscovery({
    success: function (res) {
      console.log('停止扫描蓝牙设备', res)
    }
  })
}

3. 连接蓝牙设备并发送开锁指令

连接找到的蓝牙锁设备,并发送开锁指令。

function connectToBluetoothDevice(deviceId) {
  uni.createBLEConnection({
    deviceId: deviceId,
    success: function (res) {
      console.log('连接蓝牙设备成功', res)
      sendUnlockCommand(deviceId)
    },
    fail: function (err) {
      console.error('连接蓝牙设备失败', err)
    }
  })
}

function sendUnlockCommand(deviceId) {
  // 假设蓝牙锁的服务UUID为 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',特征值UUID为 'yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy'
  const serviceUUID = 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  const characteristicUUID = 'yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy'
  
  uni.writeBLECharacteristicValue({
    deviceId: deviceId,
    serviceId: serviceUUID,
    characteristicId: characteristicUUID,
    value: new ArrayBuffer(1), // 根据实际开锁指令设置value
    success: function (res) {
      console.log('发送开锁指令成功', res)
    },
    fail: function (err) {
      console.error('发送开锁指令失败', err)
    }
  })
}

以上代码是一个简化的示例,实际开发中需要根据具体的蓝牙锁设备文档调整服务UUID、特征值UUID以及开锁指令。同时,需要考虑错误处理、连接状态管理等复杂情况。

回到顶部