微信小程序-蓝牙设备连接-蓝牙开门

引用此js文件就行了

 // 使用方式
 import bluetooth from './bluetooth.js';

 // 使用设备名称匹配蓝牙设备
 bluetooth.name = 'xxxx';
 wx.showLoading({
   title: '开门中...',
   mask : true,
 });
 await bluetooth.openBluetoothAdapter();

蓝牙设备匹配具体实现

/* eslint-disable no-underscore-dangle */
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function(bit) {
    return ('00' + bit.toString(16)).slice(-2);
  });
  return hexArr.join('');
}

/**
 * hex转ArrayBuffer
 */
function stringToBuffer(arr) {
  var length = arr.length;
  var buffer = new ArrayBuffer(length);
  var dataview = new DataView(buffer);
  for (let i = 0; i < length; i++) {
    dataview.setUint8(i, '0x' + arr[i]);
    // dataview.setUint8(i, arr[i].charAt(i).charCodeAt())
  }
  return buffer;
}

const bluetooth = {
  // 引用bluetooth时,获取后台传入的设备名称或者id
  name             : '',
  bluetoothDeviceId: '',
  // 1.初始化蓝牙模块。iOS 上开启主机/从机模式时需分别调用一次,指定对应的 mode:
  // central主机模式
  // peripheral从机模式
  async openBluetoothAdapter() {
    try {
      await wx.openBluetoothAdapter();
      this.startBluetoothDevicesDiscovery();
    } catch (error) {
      if (error.errCode === 10001) {
        wx.showToast({
          title   : '请打开蓝牙再次尝试开门',
          icon    : 'none',
          duration: 1500,
        });
        wx.onBluetoothAdapterStateChange((res) => {
          if (res.available) {
            this.startBluetoothDevicesDiscovery();
          }
        });
      }
    }
  },
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        if (res.discovering) {
          this.onBluetoothDeviceFound();
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery();
        }
      },
    });
  },

  // 开始搜寻附近的蓝牙外围设备。
  // 2.此操作比较耗费系统资源,请在搜索并连接到设备后调用 wx.stopBluetoothDevicesDiscovery 方法停止搜索。
  async startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return;
    }
    this._discoveryStarted = true;
    await wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      // 要搜索的蓝牙设备主 service 的 uuid 列表。某些蓝牙设备会广播自己的主 service 的 uuid。如果设置此参数,则只搜索广播包有对应uuid 的主服务的蓝牙设备。建议主要通过该参数过滤掉周边不需要处理的其他蓝牙设备。
      services          : ['XXXX'],
    });
    this.onBluetoothDeviceFound();
  },

  //   停止搜寻附近的蓝牙外围设备。
  //   5.若已经找到需要的蓝牙设备并不需要继续搜索时,建议调用该接口停止蓝牙搜索。
  stopBluetoothDevicesDiscovery() {
    wx.stopBluetoothDevicesDiscovery();
  },

  //   3.监听寻找到新设备的事件
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach((device) => {
      	// 设备匹配
      	// 以蓝牙设备服务 uuid进行匹配
        // if (device.advertisServiceUUIDs.some(uuid => uuid === '000018F0-0000-1000-8000-00805F9B34FB')) {
        //   this.createBLEConnection(device.deviceId, device.name);
        // }
        // 以蓝牙设备 名称进行匹配
        if (device.name === this.name) {
          this.createBLEConnection(device.deviceId, device.name);
        }
        // 以蓝牙设备id进行匹配(此id在安卓系统为mac地址唯一不变,每台iOS设备获取的设备id都不同,可以让设备厂家暴露设备mac给iOS设备进行匹配)
        // if (device.deviceId === this.bluetoothDeviceId) {
        //   this.createBLEConnection(device.deviceId, device.name);
        // }
      });
    });

    // 计时器
    this.timer = setTimeout(async() => {
      await wx.hideLoading();
      wx.showToast({
        title   : '开门超时请重试',
        icon    : 'none',
        duration: 1500,
      });
      this.closeBluetoothAdapter();
    }, 10 * 1000);
  },

  //   连接低功耗蓝牙设备。
  //   4.
  createBLEConnection(deviceId, name) {
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.getBLEDeviceServices(deviceId);
      },
    });
    this.stopBluetoothDevicesDiscovery();
  },
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this._deviceId,
    });
  },

  // 6.获取蓝牙设备所有服务(service)。
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        for (let i = 0; i < res.services.length; i++) {
          // 匹配设备厂家说明书所给的相应服务uuid
          if (res.services[i].uuid.includes('XXXX')) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
            return;
          }
        }
      },
    });
  },
  // 获取蓝牙设备某个服务中所有特征值(characteristic)
  // 7.
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i];
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            });
          }
          // 匹配设备厂家说明书上相应的可写入服务
          if (item.uuid.includes('XXXX')) {
            this._deviceId = deviceId;
            this._serviceId = serviceId;
            this._characteristicId = item.uuid;
            this.writeBLECharacteristicValue();
          }
          // if (item.properties.notify || item.properties.indicate) {
          //   wx.notifyBLECharacteristicValueChange({
          //     deviceId,
          //     serviceId,
          //     characteristicId: item.uuid,
          //     state           : true,
          //   });
          // }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res);
      },
    });
    // 操作之前先监听,保证第一时间获取数据
    // wx.onBLECharacteristicValueChange((characteristic) => {
    //   const idx = inArray(
    //     this.data.chs,
    //     'uuid',
    //     characteristic.characteristicId,
    //   )
    //   const data = {}
    //   if (idx === -1) {
    //     data[`chs[${this.data.chs.length}]`] = {
    //       uuid: characteristic.characteristicId,
    //       value: ab2hex(characteristic.value),
    //     }
    //   } else {
    //     data[`chs[${idx}]`] = {
    //       uuid: characteristic.characteristicId,
    //       value: ab2hex(characteristic.value),
    //     }
    //   }
    // data[`chs[${this.data.chs.length}]`] = {
    //   uuid: characteristic.characteristicId,
    //   value: ab2hex(characteristic.value)
    // }
    //   this.setData(data)
    // })
  },

  // 向低功耗蓝牙设备特征值中写入二进制数据。
  // 注意:必须设备的特征值支持 write 才可以成功调用。
  // 8
  async writeBLECharacteristicValue() {
    // 蓝牙写入指令
	// 此为示例
    const arr = ['fe', '12','88','55','11'];
    
    const buffer = stringToBuffer(arr);
    try {
      await wx.writeBLECharacteristicValue({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId        : this._deviceId,
        // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId       : this._serviceId,
        // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
        characteristicId: this._characteristicId,
        value           : buffer,
      });
      // 关闭之前调用的 showLoading
      await wx.hideLoading();
      wx.showToast({
        title: '开门成功',
        icon : 'none',
      });
      // 开门成功清除定时器;
      clearTimeout(this.timer);
    } catch (error) {
      console.log(`error`, error);
      wx.showToast({
        title: '开门失败请重试',
        icon : 'none',
      });
    }
    this.closeBluetoothAdapter();
  },
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter();
    this._discoveryStarted = false;
  },
};

export default bluetooth;

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是微信小程序蓝牙连接设备的代码示例: 1. 开启蓝牙适配器 ```javascript wx.openBluetoothAdapter({ success: function (res) { console.log('蓝牙适配器已打开'); }, fail: function (res) { console.log('蓝牙适配器打开失败'); } }) ``` 2. 搜索附近的蓝牙设备 ```javascript wx.startBluetoothDevicesDiscovery({ allowDuplicatesKey: true, success: function (res) { console.log('搜索附近的蓝牙设备成功'); }, fail: function (res) { console.log('搜索附近的蓝牙设备失败'); } }) ``` 3. 建立蓝牙连接 ```javascript wx.createBLEConnection({ deviceId: deviceId, success: function (res) { console.log('蓝牙连接成功'); }, fail: function (res) { console.log('蓝牙连接失败'); } }) ``` 其中,deviceId为搜索到的设备的唯一标识符。 4. 监听蓝牙连接状态 ```javascript wx.onBLEConnectionStateChange(function (res) { console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`) }) ``` 5. 向设备写入数据 ```javascript wx.writeBLECharacteristicValue({ deviceId: deviceId, serviceId: serviceId, characteristicId: characteristicId, value: buffer, success: function (res) { console.log('数据写入成功'); }, fail: function (res) { console.log('数据写入失败'); } }) ``` 其中,serviceId和characteristicId是设备的服务和特征值的唯一标识符,buffer是要写入的数据。 以上是微信小程序蓝牙连接设备的简单示例代码,具体实现还需要根据实际情况进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值