The uni-app program implements display of Bluetooth communication and displays data received by Bluetooth

To implement Bluetooth communication and display the received data, you need to use the Bluetooth plug-in provided by uni-app. The following is a simple example program:

  1. Add the Bluetooth plug-in configuration in the manifest.json file.
{
    
    
  "mp-weixin": {
    
    
    "plugins": {
    
    
      "wx589698e9c8539a7c": {
    
    
        "version": "1.1.1",
        "provider": "wx589698e9c8539a7c"
      }
    }
  }
}
  1. Add a button to the page for connecting to a Bluetooth device.
<template>
  <view class="content">
    <view class="btn" @tap="connect">
      {
   
   {connected ? '断开连接' : '连接蓝牙'}}
    </view>
    <view class="receive">{
   
   {receiveMsg}}</view>
  </view>
</template>
  1. Define a data object in the component's script, containing information such as Bluetooth connection status, received data, and Characteristic objects, and define a method to connect or disconnect the Bluetooth device and monitor the received data.
<script>
export default {
    
    
  data() {
    
    
    return {
    
    
      connected: false,
      receiveMsg: '',
      deviceId: '', // 设备ID
      serviceId: '', // 服务ID
      characteristicId: '', // Characteristic对象ID
    }
  },
  methods: {
    
    
    // 连接蓝牙设备
    connect() {
    
    
      if (this.connected) {
    
    
        // 断开蓝牙连接
        wx.closeBLEConnection({
    
    
          deviceId: this.deviceId,
          success: () => {
    
    
            console.log('closeBLEConnection success')
            this.connected = false
          }
        })
      } else {
    
    
        wx.openBluetoothAdapter({
    
    
          success: (res) => {
    
    
            console.log('openBluetoothAdapter success', res)
            wx.startBluetoothDevicesDiscovery({
    
    
              services: [], //要搜索的服务列表,为空表示搜索所有服务
              success: (res) => {
    
    
                console.log('startBluetoothDevicesDiscovery success', res)
                wx.onBluetoothDeviceFound((res) => {
    
    
                  console.log('onBluetoothDeviceFound', res)
                  //检索到设备后,连接设备
                  if (res.devices[0].deviceId === '设备ID') {
    
    
                    this.deviceId = res.devices[0].deviceId
                    wx.createBLEConnection({
    
    
                      deviceId: this.deviceId,
                      timeout: 5000, //超时时间(单位ms),过了这个时间如果还没连接上就会返回失败
                      success: () => {
    
    
                        console.log('createBLEConnection success')
                        //连接成功后,获取蓝牙设备的所有服务
                        wx.getBLEDeviceServices({
    
    
                          deviceId: this.deviceId,
                          success: (res) => {
    
    
                            console.log('getBLEDeviceServices success', res)
                            for (let service of res.services) {
    
    
                              if (service.uuid === '服务UUID') {
    
    
                                this.serviceId = service.uuid
                                // 连接服务后,获取Characteristic对象
                                wx.getBLEDeviceCharacteristics({
    
    
                                  deviceId: this.deviceId,
                                  serviceId: this.serviceId,
                                  success: (res) => {
    
    
                                    console.log('getBLEDeviceCharacteristics success', res)
                                    const characteristic = res.characteristics.find(item => item.uuid === '特征UUID')
                                    this.characteristicId = characteristic.uuid
                                    // 监听接收到的数据
                                    wx.onBLECharacteristicValueChange((res) => {
    
    
                                      const receiveData = ab2str(res.value)
                                      console.log('接收到的数据:', receiveData)
                                      this.receiveMsg += receiveData
                                    })
                                    // 打开notify
                                    wx.notifyBLECharacteristicValueChange({
    
    
                                      deviceId: this.deviceId,
                                      serviceId: this.serviceId,
                                      characteristicId: this.characteristicId,
                                      state: true,
                                      success: (res) => {
    
    
                                        console.log('notifyBLECharacteristicValueChange success', res)
                                        this.connected = true
                                      }
                                    })
                                  }
                                })
                              }
                            }
                          }
                        })
                      },
                      fail: (res) => {
    
    
                        console.log('createBLEConnection failed', res)
                      }
                    })
                  }
                })
              }
            })
          },
          fail: (res) => {
    
    
            console.log('openBluetoothAdapter failed', res)
          }
        })
      }
    }
  }
}

// ArrayBuffer转为字符串
function ab2str(buf) {
    
    
  return String.fromCharCode.apply(null, new Uint8Array(buf));
}
</script>
  1. The style part can be added by yourself, and the final effect is that after clicking the button, you can connect or disconnect the Bluetooth device and display the received data. Among them, you need to replace 设备ID, 服务UUID, 特征UUIDwith the actual device ID, service UUID and characteristic UUID.

Guess you like

Origin blog.csdn.net/weixin_42317757/article/details/131321944
Recommended