uniapp 蓝牙连接教程

在uniapp中实现蓝牙连接需要使用uni-app插件市场提供的插件,如"uni-bluetooth-serial"插件。以下是实现蓝牙连接的通用步骤:

  1. 安装插件

通过手机App中心,搜索并安装uniapp的蓝牙插件。

  1. 初始化蓝牙设备

在前端Vue组件,初始化蓝牙设备,并使用uni.openBluetoothAdapter方法开启蓝牙模块。这是蓝牙设备连接的基础。

// 创建Vue对象
const app = new Vue({
  el: '#app',
  data() {
    return {
      devices: [],
      connectedDevice: null,
      serviceId: "0000ffe0-0000-1000-8000-00805f9b34fb",
      writeCharacteristicId: "0000ffe1-0000-1000-8000-00805f9b34fb",
    }
  },
  methods: {
    // 打开蓝牙
    openBluetooth(){
      uni.openBluetoothAdapter({
        success: () => {
          this.logs.push('开启蓝牙成功')
          // 立即开始扫描设备
          this.startScanDevices()
        },
        fail: (res) => {
          this.logs.push(`开启蓝牙失败[${res.errCode}]: ${res.errMsg}`)
        }
      })
    }
  }
})
  1. 设备扫描和连接

使用uni.startBluetoothDevicesDiscovery方法扫描附近的蓝牙设备。在收到设备列表后,可从列表中选择要连接的设备,设备连接信号管理可以通过uni.onBluetoothDeviceFound函数进行设置。调用uni.createBLEConnection方法与所选蓝牙设备建立连接。连接成功后,获得设备服务列表,并连接所需的服务和特征。对于不同类型的蓝牙设备,有不同的连接方式。下面是一个通用的蓝牙设备连接示例:

// 设备发现更新
  onDeviceFound(e) {
    // 扫描到的设备
    const device = e.devices[0]
    
    // 判断是否已存在列表中
    if(!this.deviceIsExist(device.deviceId)) {
      this.devices.push(device)
    }
  },
  // 连接设备
  connect(deviceId) {
    uni.createBLEConnection({
      deviceId: deviceId,
      success: (res) => {
        this.connectedDevice = res
        // 获取设备的服务列表
        this.getBLEDeviceServices(deviceId)
      },
      fail: (res) => {
        console.log('连接设备失败', res)
      }
    })
  },
  // 获取设备的服务列表
  getBLEDeviceServices(deviceId) {
    uni.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        // 打印日志
        this.logs.push('获取服务列表成功')
        console.log('设备服务列表', res.services)
        // 获取设备的特征值
        res.services.forEach(service => {
          if (service.uuid.toUpperCase() == "FFF0") {
            this.getBLEDeviceCharacteristics(deviceId, service.uuid)
          }
        })
      },
      fail: (res) => {
        console.log('获取服务列表失败', res)
      }
    })
  },
  // 获取设备的特征值
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    uni.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('设备特征值列表', res.characteristics)
        
        // 遍历特征值,找到所需特征
        res.characteristics.forEach(characteristic => {
          // 打印日志
          console.log('设备特征值', characteristic)
          if

猜你喜欢

转载自blog.csdn.net/qq_36016297/article/details/129833114