微信小程序蓝牙低功率完整代码,复制直接用

 1.封装蓝牙连接js文件

function BLE(options) {
  this.options = options || { locator: {} };
}
  
 function ab2hex(buffer) {
  const hexArr = Array.prototype.map.call(
   new Uint8Array(buffer),
   function (bit) {
    return ('00' + bit.toString(16)).slice(-2)
   }
  )
  return hexArr.join('-')
 };
 //十六进制转换为arraybuffer
 function hex2ArrayBuffer(hex_str){
  // let hex_str = 'AA5504B10000B5'
  let typedArray = new Uint8Array(hex_str.match(/[\da-f]{2}/gi).map(function (h) {
    return parseInt(h, 16)
  }))
  let buffer = typedArray.buffer
  return buffer
};
 let data={
    deviceId:null,
    serviceId:null,
    characteristicId:[],
 };
 BLE.prototype = {
  open:function(callback){
    wx.openBluetoothAdapter({
      success: (res) => {
        callback(res)
      },
      fail: (err) => {
        console.log('初始化失败', err)
        wx.showToast({
          title: '请确保已打开蓝牙',
          icon: 'none'
        })
      }
    })
  },
  scan:function(callback){
    wx.startBluetoothDevicesDiscovery({
      success: (res) => {
        console.log('开始扫描BLE设备', res);
        wx.onBluetoothDeviceFound((res) => {
          callback(res)
        })
      },
      fail: (err) => {
        console.log('扫描BLE设备失败', err);
      }
    });
  },
  connect:function(deviceId,callback){
    data.deviceId=deviceId
    //创建连接
    wx.createBLEConnection({
      deviceId: deviceId,
      success: (res) => {
        console.log('连接成功', res)
        callback({code:1})
      },
      fail: (err) => {
        console.log(err)
        callback({code:0})
      }
    })
  },
  write: function (deviceId,value, callback) {//写入数据  成功 调用callback();
    let buffer=hex2ArrayBuffer(value)
    wx.getBLEDeviceServices({
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId: deviceId,
      success(res) {
        res.services.forEach(item=>{
          wx.getBLEDeviceCharacteristics({
            // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
            deviceId: deviceId,
            // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
            serviceId: item.uuid,
            success(res) {
              for (let i = 0; i < res.characteristics.length; i++) {
                let it = res.characteristics[i]
                if (it.properties.write == true) {
                  wx.writeBLECharacteristicValue({
                    deviceId: deviceId,
                    serviceId: item.uuid,
                    characteristicId: it.uuid,
                    value: buffer,
                    success: function (res) {
                      console.log(res);
                    },
                    fail: function (res) {
                      console.log(res);
                    }
                  })
                }
                if (it.properties.notify == true) {
                  wx.notifyBLECharacteristicValueChange({
                    characteristicId: it.uuid,
                    deviceId: deviceId,
                    serviceId: item.uuid,
                    state: true,
                    success: (res) => {
                      console.log("监听特征值", res)
                      // 开始监听发送值
                      wx.onBLECharacteristicValueChange((res) => {
                        console.log("监听",res)
                        let text=ab2hex(res.value)
                        wx.showToast({
                          title: '成功',
                          icon:'success'
                        })
                        callback(text);
                      })
                    },
                    fail:(err)=>{
                      wx.showToast({
                        title: '失败',
                        icon:'error'
                      })
                    }
                  })
                }
              }
              
            }
          })
        })
      }
    })
  },
  read:function(deviceId,callback){
    wx.onBLECharacteristicValueChange((res) => {
      console.log(res.value)
      let text=ab2hex(res.value)
      console.log(text)
      callback(text);
    });
    wx.readBLECharacteristicValue({
      characteristicId: data.characteristicId.readId,
      deviceId: deviceId,
      serviceId: data.serviceId,
      success: (res) => {
        console.log("读取",res)
      },
      fail:(err)=>{
        console.log(err)
      }
    })
  },
  close: function (deviceId, callback) {//关闭蓝牙  成功 调用callback();
    wx.closeBLEConnection({
      deviceId: deviceId,
      success: (res) => {
        console.log('断开连接成功', res)
        callback({code:1})
      },
      fail: (err) => {
        console.log(err)
        callback({code:0})
      }
    })
  },
  stop:function(){
    wx.stopBluetoothDevicesDiscovery({
      success (res) {
        console.log(res)
      }
    })
  },
 }
  
 exports.BLE=BLE;

2.在需要的地方引用

//导入蓝牙
const Ble = require('../../utils/bluetooth.js');
let ble = new Ble.BLE();

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值