Skip to content
js
// 1.初始化蓝牙
  openBluetoothAdapter() {
    const _this = this
    wx.openBluetoothAdapter({
      success(res) {
        wx.getBluetoothAdapterState({
          success(res) {
            if (res.available) {
              if (res.discovering) {
                wx.stopBluetoothDevicesDiscovery({
                  success: function (res) {
                    _this.getBluetoothDevices()
                  },
                })
              } else {
                _this.getBluetoothDevices()
              }
            } else {
              wx.showModal({
                title: '提示',
                content: '本机蓝牙不可用',
                showCancel: false,
              })
            }
          },
        })
      },
      fail(err) {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '蓝牙初始化失败,请打开蓝牙后重试',
          showCancel: false,
        })
      },
    })
  },
  // 2.搜索设备
  getBluetoothDevices() {
    const _this = this
    wx.startBluetoothDevicesDiscovery({
      success(res) {
        wx.onBluetoothDeviceFound((res) => {
          res.devices.forEach((device) => {
            if (!device.name && !device.localName) {
              return
            }
            const foundDevices = _this.data.device_list
            const idx = _this.inArray(foundDevices, 'deviceId', device.deviceId)
            const data = {}
            if (idx === -1) {
              data[`device_list[${foundDevices.length}]`] = device
            } else {
              data[`device_list[${idx}]`] = device
            }
            _this.setData(data)
          })
        })
        setTimeout(() => {
          wx.stopBluetoothDevicesDiscovery()
        }, 20000)
      },
      fail(err) {
        console.log('初始化蓝牙失败')
        console.error(err)
      },
    })
  },
  // 3.连接设备
  handleConnect(e) {
    const _this = this
    // 停止搜索蓝牙
    wx.stopBluetoothDevicesDiscovery()
    const info = e.currentTarget.dataset.item
    this.setData(
      {
        blueInfo: info,
        deviceId: info.deviceId,
        deviceValue: info.name,
      },
      () => {
        wx.showLoading({
          title: '正在连接',
        })
        wx.createBLEConnection({
          deviceId: info.deviceId,
          success(res) {
            _this.getSeviceId(info.deviceId)
            wx.setStorageSync('currentBle', info)
          },
          fail(err) {
            wx.hideLoading()
            wx.showToast({
              title: '连接失败',
              icon: 'error',
            })
          },
        })
      }
    )
  },
  // 4.获取蓝牙设备的服务uuid
  getSeviceId(deviceId) {
    const _this = this
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: function (res) {
        const tar = res.services.filter((item) => item.isPrimary)
        res.services.forEach((item) => {
          if (item.isPrimary && S_UUID.includes(item.uuid)) {
            _this.setData(
              {
                servicesId: item.uuid,
              },
              () => {
                _this.getBLEDeviceCharacteristics()
              }
            )
          }
        })
        console.log(tar, '------服务')
      },
      fail: function (e) {
        console.log(e)
      },
    })
  },
  // 获取特征值
  getBLEDeviceCharacteristics() {
    const _this = this
    wx.getBLEDeviceCharacteristics({
      deviceId: _this.data.deviceId,
      serviceId: _this.data.servicesId,
      success: (res) => {
        console.log(res.characteristics, '-----特征值')
        if (res.characteristics && res.characteristics.length) {
          res.characteristics.forEach((item) => {
            if (C_UUID.includes(item.uuid)) {
              if (item.properties.notify) {
                _this.startNotice(item.uuid)
              }
              if (item.properties.write) {
                _this.setData({
                  writeInfo: item,
                })
              }
            }
          })
          wx.hideLoading()
          wx.showToast({
            title: '连接成功',
          })
          _this.onClosePop()
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      },
    })
  },
  // 5.获取蓝牙设备的特征值
  getCharacteId() {
    const _this = this
    wx.getBLEDeviceCharacteristics({
      deviceId: _this.data.deviceId,
      serviceId: _this.data.servicesId,
      success(res) {
        const tar = res.characteristics.filter((item) => item.properties.notify)
        console.log(res.characteristics, '-----特征值')
        res.characteristics.forEach((item) => {
          if (item.properties.notify) {
            _this.startNotice(item.uuid)
          }
          if (item.properties.write) {
            _this.setData({
              writeInfo: item,
            })
          }
        })
        wx.hideLoading()
        wx.showToast({
          title: '连接成功',
        })
      },
      fail(res) {
        console.log('设备特征值err--->', res)
      },
    })
  },
  // 监听数据传输
  startNotice(uuid) {
    const _this = this
    console.log(_this.data.deviceId)
    console.log(_this.data.servicesId)
    console.log(uuid)
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      deviceId: _this.data.deviceId,
      serviceId: _this.data.servicesId,
      characteristicId: uuid,
      success(res) {
        wx.onBLECharacteristicValueChange(function (data) {
          if (data.value) {
            // console.log(_this.ab2hex(data.value), '蓝牙响应消息')
            console.log(_this.hexToString(_this.ab2hex(data.value)))
            if (_this.data.writeCmd) {
              _this.setData({
                bleRes: _this.data.bleRes + _this.hexToString(_this.ab2hex(data.value)),
              })
            }
            if (_this.ab2hex(data.value) == '23213c44415459303023213e') {
              _this.writeBle('#!<REFR01#!>')
            }
          }
        })
      },
      fail(err) {
        console.log('监听数据失败', err)
      },
    })
  },