uniapp开发蓝牙功能实战教程

在uniapp中开发蓝牙功能时,如何实现设备的搜索、连接和数据传输?有没有完整的代码示例可以参考?另外,在安卓和iOS平台上会不会有兼容性问题?

2 回复

uniapp蓝牙开发步骤:

  1. 引入uni蓝牙API
  2. 初始化蓝牙模块
  3. 搜索设备并获取设备列表
  4. 连接目标设备
  5. 获取服务与特征值
  6. 读写数据 注意:需配置manifest.json蓝牙权限,真机调试。

Uniapp 蓝牙功能开发实战教程

环境准备

  1. 确保设备支持蓝牙功能
  2. 在 manifest.json 中添加蓝牙权限:
{
  "mp-weixin": {
    "requiredPrivateInfos": ["getBluetoothDevices"]
  }
}

核心步骤

1. 初始化蓝牙模块

// 检查蓝牙适配器状态
uni.openBluetoothAdapter({
  success: (res) => {
    console.log('蓝牙适配器初始化成功')
    this.startDiscovery()
  },
  fail: (err) => {
    console.log('蓝牙初始化失败', err)
  }
})

2. 搜索蓝牙设备

startDiscovery() {
  uni.startBluetoothDevicesDiscovery({
    services: [], // 指定服务UUID,空数组表示搜索所有设备
    allowDuplicatesKey: false,
    success: (res) => {
      console.log('开始搜索设备')
      this.listenDevices()
    }
  })
}

3. 监听发现设备

listenDevices() {
  uni.onBluetoothDeviceFound((devices) => {
    devices.devices.forEach(device => {
      if (device.name && !this.deviceList.some(d => d.deviceId === device.deviceId)) {
        this.deviceList.push(device)
      }
    })
  })
}

4. 连接设备

connectDevice(deviceId) {
  uni.createBLEConnection({
    deviceId: deviceId,
    success: (res) => {
      console.log('连接成功')
      this.getServices(deviceId)
    },
    fail: (err) => {
      console.log('连接失败', err)
    }
  })
}

5. 获取服务

getServices(deviceId) {
  uni.getBLEDeviceServices({
    deviceId: deviceId,
    success: (res) => {
      res.services.forEach(service => {
        if (service.isPrimary) {
          this.getCharacteristics(deviceId, service.uuid)
        }
      })
    }
  })
}

6. 获取特征值

getCharacteristics(deviceId, serviceId) {
  uni.getBLEDeviceCharacteristics({
    deviceId: deviceId,
    serviceId: serviceId,
    success: (res) => {
      res.characteristics.forEach(char => {
        // 监听特征值变化
        if (char.properties.notify) {
          uni.notifyBLECharacteristicValueChange({
            deviceId: deviceId,
            serviceId: serviceId,
            characteristicId: char.uuid,
            state: true
          })
        }
      })
    }
  })
}

7. 监听数据接收

uni.onBLECharacteristicValueChange((res) => {
  const value = res.value
  // 处理接收到的数据
  console.log('收到数据:', this.ab2hex(value))
})

// ArrayBuffer转16进制字符串
ab2hex(buffer) {
  const hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    bit => ('00' + bit.toString(16)).slice(-2)
  )
  return hexArr.join('')
}

8. 发送数据

sendData(deviceId, serviceId, characteristicId, data) {
  uni.writeBLECharacteristicValue({
    deviceId: deviceId,
    serviceId: serviceId,
    characteristicId: characteristicId,
    value: this.str2ab(data),
    success: (res) => {
      console.log('发送成功')
    }
  })
}

// 字符串转ArrayBuffer
str2ab(str) {
  const buffer = new ArrayBuffer(str.length)
  const dataView = new DataView(buffer)
  for (let i = 0; i < str.length; i++) {
    dataView.setUint8(i, str.charCodeAt(i))
  }
  return buffer
}

注意事项

  1. 安卓和iOS在蓝牙权限上有所差异
  2. 设备连接需要用户手动操作触发
  3. 及时关闭蓝牙搜索以节省电量
  4. 注意错误处理和超时机制

完整示例

建议在实际项目中封装蓝牙管理类,统一处理连接状态、数据收发和错误处理。

回到顶部