微信小程序 蓝牙(点击出现弹窗,下拉选择蓝牙,点击即可传输数据)

不少博主都写过蓝牙小程序,但都是类似于蓝牙调试助手,使用起来很不方便,(多页面跳转,一个个自己手动选择uuid,serviceid等,给初学者带来了很大的困扰,或者直接写死,不知道咋改)按照正常的逻辑,蓝牙其实就是点击个图标,弹出来搜索到的周围蓝牙,然后点击蓝牙,之后就可以正常传输数据就成。在完成自己的第一个小程序时候,就用到了类似的功能。记录下,希望给大家参考。
实验效果:
在这里插入图片描述刚点击进去的图片
在这里插入图片描述点击蓝牙测试按钮触发了检测自己设备蓝牙是否打开,搜索周围蓝牙,以及监听函数等。
在这里插入图片描述在弹窗里滑动选择自己需要的蓝牙,进行点击,既可以连接。为了更直观显示,我把连接到的蓝牙名字发送到了前端进行了显示
在这里插入图片描述点击发送按钮,触发书写函数,进行发送数据。同时监听到发送的和接收到的内容。

index.js:37 
index.js:40 已蓝牙适配器
index.js:44 已查看蓝牙适配器状态
index.js:50 已搜索设备
lanya.js:78 获取到的蓝牙设备为 {errMsg: "getBluetoothDevices:ok", devices: Array(2)}
lanya.js:79 长度测试 2
lanya.js:84 蓝牙名 EWFF56DD4A69B7
index.js:62 此时temp的值 []
index.js:56 获取到的蓝牙设备名字********************************* {deviceId: "FF:56:DD:4A:69:B7", name: "EWFF56DD4A69B7", RSSI: -78, advertisData: ArrayBuffer(8), advertisServiceUUIDs: Array(1),}
index.js:62 此时temp的值 [{}]
index.js:37 
index.js:40 已蓝牙适配器
index.js:44 已查看蓝牙适配器状态
index.js:50 已搜索设备
lanya.js:78 获取到的蓝牙设备为 {errMsg: "getBluetoothDevices:ok", devices: Array(8)}
lanya.js:79 长度测试 8
lanya.js:84 蓝牙名 EWFF56DD4A69B7
lanya.js:84 蓝牙名 82200A090A06
lanya.js:84 蓝牙名 82200A093366
lanya.js:84 蓝牙名 82200A090ED7
lanya.js:84 蓝牙名 8200000116B8
lanya.js:84 蓝牙名 82200A093E63
index.js:62 此时temp的值 [{}]
index.js:56 获取到的蓝牙设备名字********************************* {deviceId: "FF:56:DD:4A:69:B7", name: "EWFF56DD4A69B7", RSSI: -77, advertisData: ArrayBuffer(8), advertisServiceUUIDs: Array(1),}
index.js:62 此时temp的值 (2) [{}, {}]
index.js:56 获取到的蓝牙设备名字********************************* {deviceId: "82:20:0A:09:0A:06", name: "82200A090A06", RSSI: -83, advertisData: ArrayBuffer(8), advertisServiceUUIDs: Array(1),}
index.js:62 此时temp的值 (3) [{}, {}, {}]
index.js:56 获取到的蓝牙设备名字********************************* {deviceId: "82:20:0A:09:33:66", name: "82200A093366", RSSI: -81, advertisData: ArrayBuffer(8), advertisServiceUUIDs: Array(1),}
index.js:62 此时temp的值 (4) [{}, {}, {}, {}]
index.js:56 获取到的蓝牙设备名字********************************* {deviceId: "82:20:0A:09:0E:D7", name: "82200A090ED7", RSSI: -92, advertisData: ArrayBuffer(8), advertisServiceUUIDs: Array(1),}
index.js:62 此时temp的值 (5) [{}, {}, {}, {}, {}]
index.js:56 获取到的蓝牙设备名字********************************* {deviceId: "82:00:00:01:16:B8", name: "8200000116B8", RSSI: -86, advertisData: ArrayBuffer(8), advertisServiceUUIDs: Array(1),}
index.js:62 此时temp的值 (6) [{}, {}, {}, {}, {}, {}]
index.js:56 获取到的蓝牙设备名字********************************* {deviceId: "82:20:0A:09:3E:63", name: "82200A093E63", RSSI: -90, advertisData: ArrayBuffer(8), advertisServiceUUIDs: Array(1),}
index.js:62 此时temp的值 (7) [{}, {}, {}, {}, {}, {}, {}]
index.js:62 此时temp的值 (7) [{}, {}, {}, {}, {}, {}, {}]
index.js:78 severceUUID是 ["00001000-0000-1000-8000-00805F9B34FB"]
index.js:79 截取测试 1000
index.js:88 此时deviceId的值是 FF:56:DD:4A:69:B7
index.js:89 此时data里的deviceId是 FF:56:DD:4A:69:B7
index.js:90 此时data里的serviceUUIDSamll是 1000
index.js:104 已连接设备
index.js:107 已停止扫描设备
index.js:135 已经完成了获取服务特征值
index.js:136 延迟3秒前,此时的serciceId是 
lanya.js:136 停止扫描设备的函数已启用
index.js:96 {errCode: 0, errMsg: "createBLEConnection:ok"}
index.js:114 已进入第三层
index.js:115 获取到的设备名字是: {errMsg: "getBLEDeviceServices:ok", services: Array(5), errCode: 0}
index.js:118 打印出来所有的result.services[i].uuid 00001000-0000-1000-8000-00805F9B34FB
index.js:120 服务已找到
index.js:118 打印出来所有的result.services[i].uuid 0000FE59-0000-1000-8000-00805F9B34FB
index.js:120 服务已找到
index.js:118 打印出来所有的result.services[i].uuid 0000180A-0000-1000-8000-00805F9B34FB
index.js:120 服务已找到
index.js:118 打印出来所有的result.services[i].uuid 00001800-0000-1000-8000-00805F9B34FB
index.js:120 服务已找到
index.js:118 打印出来所有的result.services[i].uuid 00001801-0000-1000-8000-00805F9B34FB
index.js:120 服务已找到
index.js:138 延时3秒后,此时的serviceId是 00001000-0000-1000-8000-00805F9B34FB
index.js:143 {errMsg: "getBLEDeviceCharacteristics:ok", characteristics: Array(5), errCode: 0}
index.js:146 获取到的特征值id:00001001-0000-1000-8000-00805F9B34FB
index.js:154 此时的notifyCharacteristicId 
index.js:160 开启write的characteristicId:00001001-0000-1000-8000-00805F9B34FB
index.js:167 0
index.js:146 获取到的特征值id:00001002-0000-1000-8000-00805F9B34FB
index.js:148 开启notify的characteristicId:00001002-0000-1000-8000-00805F9B34FB
index.js:154 此时的notifyCharacteristicId 00001002-0000-1000-8000-00805F9B34FB
index.js:167 0
index.js:146 获取到的特征值id:00001003-0000-1000-8000-00805F9B34FB
index.js:154 此时的notifyCharacteristicId 00001002-0000-1000-8000-00805F9B34FB
index.js:146 获取到的特征值id:00001004-0000-1000-8000-00805F9B34FB
index.js:154 此时的notifyCharacteristicId 00001002-0000-1000-8000-00805F9B34FB
index.js:167 0
index.js:146 获取到的特征值id:00001005-0000-1000-8000-00805F9B34FB
index.js:154 此时的notifyCharacteristicId 00001002-0000-1000-8000-00805F9B34FB
index.js:167 0
index.js:181 此时的notifyCharacteristicId&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& 00001002-0000-1000-8000-00805F9B34FB
index.js:188 {errCode: 0, errMsg: "notifyBLECharacteristicValueChange:ok"}
index.js:228 read读取成功
lanya.js:254 读取低功耗蓝牙的特征值得二进制数值成功
index.js:210 write函数内部的notity 00001001-0000-1000-8000-00805F9B34FB
index.js:212 $HC12,02
index.js:249 Uint8Array(8) [36, 72, 67, 49, 50, 44, 48, 50]
index.js:223 {errCode: 10012, errMsg: "writeBLECharacteristicValue:fail:operate time out"}

为了更直观,我贴出我连接时候真机调试显示的信息。
同时在串口助手里面,我也进行了测试。
在这里插入图片描述
然后我用串口助手发送12345进行了测试
在这里插入图片描述是可以监听到的
下面便是完整的代码:

index.wxml
<view wx:if="{{showname}}">{{name}}</view>
<button bindtap="bluetooth">蓝牙测试</button>
<view class="modal-mask" bindtap="hideModal" catchtouchmove="preventTouchMove" wx:if="{{showble}}"></view>
<view class="modal-dialog" wx:if="{{showble}}">
  <view class="modal-title">可连接的蓝牙</view>
  <view class="modal-content">
    <scroll-view scroll-y="true" style="height:150px;width:100%">
      <view wx:for="{{devicesname}}" wx:key="key" bindtap="connect" data-dev="{{item}}">
        <button class="info">
          <view class="name" style="white-space: pre-wrap;width:500rpx;height:40rpx" >{{item.name}}</view>
        </button>
      </view>
    </scroll-view>
  </view>
  <view class="modal-footer">
    <view class="btn-cancel" bindtap="onCancel" data-status="cancel">取消</view>
    <view class="btn-confirm" bindtap="onConfirm" data-status="confirm">确定</view>
  </view>
</view>
<button bindtap="sendmessage">发送数据</button>

格式部分:index.wxss

/**index.wxss**/
/* pages/search/search.wxss */
/**index.wxss**/
/* pages/search/search.wxss */
.label {
  height: 40px;
  line-height: 40px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
  background-color: #2d2d2d;
  color: #EEE;
}
.item {
  position: relative;
  padding: 10px;
  margin: 5px 5px;
  height: 90px;
  border-bottom: 1px solid #D0D0D0;
  display: flex;
  flex-direction: column;
  align-items: left;
  justify-content: space-between;
  box-sizing: border-box;
}
.item .rss {
  position: absolute;
  height: 70px;
  line-height: 70px;
  right: 10px;
}
.item .name {
  height: 30px;
  line-height: 30px;
  border: 3rpx solid #faca82;
}
.item .uuid {
  padding-right: 50px;
  height: 40px;
  line-height: 1.5;
  font-size: 12px;
}
.showModal{
  position:absolute;
  height:50px;
  left:30%;
  width:40%;
  top:40%;
  background: rgb(95, 228, 83);
  color:#fff;
  font-size: 20px;
}
/*以下全是弹窗样式*/
.modal-mask {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: #000;
  opacity: 0.5;
  overflow: hidden;
  z-index: 9000;
  color: #fff;
}
.modal-dialog {
  width: 80%;
  overflow: hidden;
  position: fixed;
  top: 40%;
  left: 0;
  z-index: 9999;
  background: #f9f9f9;
  margin-top: -180rpx;
  margin-left: 10%;
  border-radius: 36rpx;
}
.modal-title {
  padding-top: 30rpx;
  font-size: 20px;
  color: #030303;
  text-align: center;
}
.modal-title-sc {
  padding-top: 10rpx;
  font-size: 15px;
  color: #bebcbc;
  text-align: center;
}
.modal-content {
  /* padding: 0rpx 0rpx; */
 padding:0rpx 0rpx;
 height: 400rpx;
 text-align: left;
}
.info{
  height:40px;
  left:-120rpx;
  right: -150rpx;
  text-align:left;
  font-size:35rpx;
  color:#0a0000;
}
.info::after{
  border: 0px;
}
.name_List{
  position:absolute;
  left:0%;
  width:150%;
  text-align: left;
  border: 3rpx solid #faca82;
}
.quantity_List{
  position:absolute;
  left:40%;
  width:50%;
  text-align: left;
}
.reason_List{
  position:absolute;
  left:50%;
  width:50%;
  text-align: right;
  overflow: hidden;
}
.modal-content-return{
  padding: 15rpx 32rpx;
  font-size: 15px;
  color: #bebcbc;
}
.modal-footer {
  display: flex;
  flex-direction: row;
  height: 86rpx;
  border-top: 1px solid #dedede;
  font-size: 34rpx;
  line-height: 86rpx;
}
.btn-cancel {
  width: 100%;
  color: #666;
  text-align: center;
  border-right: 1px solid #dedede;
}
.btn-confirm {
  width: 50%;
  color: #ec5300;
  text-align: center;
}
.bluetooth{
  display: flex;
  position: relative;
  left: 55rpx;
  top: 50px;
}
.blelist{
  border: 3rpx solid #faca82;
  
}

逻辑部分:index.js

const app = getApp()
// var util = require('../utils/util.js')
import{openBluetoothAdapter,getBluetoothAdapterState,startBluetoothDevicesDiscovery,getBluetoothDevices,createBLEConnection,
  stopBluetoothDevicesDiscovery,getBLEDeviceServices,getBLEDeviceCharacteristics,notifyBLECharacteristicValueChange,
  writeBLECharacteristicValue,readBLECharacteristicValue,closeBluetoothAdapter} 
  from "../../request/lanya.js";
Page({
  data: {
    obj:'',
    showname:false,
    BluetoothState:false,
    temp:[],
    name:[],//在界面显示出来连接的蓝牙的名字
    showble:false,//初始化蓝牙弹窗不弹出啊
      //--------------------------蓝牙部分开始----------------------------------------
      devices:'',
      devicename:'',//存储搜索到的蓝牙设备的名字
      //蓝牙相关信息
        deviceId:'',//蓝牙设备id,每个蓝牙都不一样
        serviceUUIDSamll:'',//蓝牙可用服务id,用于查询我们要寻找的服务
        serviceId:'',//蓝牙服务id全名,用作参数调用小程序api自动获取
        notifyCharacteristicId:'',//该服务的notify特征值 可自动获取
        writeCharacteristicId:'',//该服务的write特征值 可自动获取
        readCharactersticId:'', 
        msg:'ABCD',//要给蓝牙发送的数
        name:'',
        //--------------------------蓝牙部分结束----------------------------------------
  },
  async bluetooth(){
    var that=this;
    //1.打开弹窗
    that.setData({
      showble:true
    })
    //对蓝牙进行初始化等操纵。找到可以连接的设备
   
    console.log(this.data.deviceId)
    //1.打开蓝牙适配器
  var res=await openBluetoothAdapter();
   console.log("已蓝牙适配器")
   
    //2.查看蓝牙适配器状态
   var res=await getBluetoothAdapterState();
    console.log("已查看蓝牙适配器状态")
    that.setData({
      BluetoothState:true
    })
    //3.搜索设备
    res =await startBluetoothDevicesDiscovery();
    console.log("已搜索设备")
    //4.获取蓝牙设备信息,停一秒再获取
    res =await getBluetoothDevices();
    //过滤无效的蓝牙名字,把有效的发送到前端进行选择
    for(var i=0;i<res.devices.length;i++){
      if(res.devices[i].name!='未知设备'){
        console.log('获取到的蓝牙设备名字*********************************',res.devices[i]) 
        that.data.temp.push(res.devices[i])
        // that.setData({
        //   devicesname:res.devices[i]
        // })
      }
      console.log('此时temp的值',that.data.temp)
          that.setData({
          devicesname:that.data.temp
        })
    }
  },
//连接函数
async connect(event) {
  var that=this;
  //获取到点击的那个蓝牙的各种参数
  if (that.data.BluetoothState) {
    const deviceId =event.currentTarget.dataset.dev.deviceId
    const severceUUID=event.currentTarget.dataset.dev.advertisServiceUUIDs
    const name=`连接到的蓝牙名字:`+event.currentTarget.dataset.dev.name

    console.log('severceUUID是',severceUUID)
    console.log('截取测试',severceUUID[0].substring(4,8))
    that.setData({
      name:name,
      deviceId:String(deviceId),
      serviceUUIDSamll:String(severceUUID[0].substring(4,8))
    })
    wx.showLoading({
      title: '正在连接...',
    })
 console.log('此时deviceId的值是',deviceId)
 console.log('此时data里的deviceId是',that.data.deviceId)
 console.log('此时data里的serviceUUIDSamll是',that.data.serviceUUIDSamll)
  }
  // res=await createBLEConnection(that.data.deviceId)
      //5.连接设备
   await   wx.createBLEConnection({
        deviceId:that.data.deviceId,
        success: (result) => {
          console.log(result)
          wx.showToast({
            title: '已连接成功',
            icon:'success',
            duration:2000
          })
        },
      })
      console.log("已连接设备")
     //6.停止扫描设备
 await  stopBluetoothDevicesDiscovery();
     console.log("已停止扫描设备")
       //7.获取连接设备的service服务

var result=await getBLEDeviceServices(that.data.deviceId);
for(let i=0;i<result.services.length;i++){
  //把服务id放到数组中
  console.log('打印出来所有的result.services[i].uuid',result.services[i].uuid)
  if(result.services[i].uuid.toUpperCase().indexOf(that.data.serviceUUIDSamll)!=-1){
    console.log("服务已找到")
    if(result.services[i].uuid.substring(4,8)=='1000')
    {
      console.log('获取到的serviceId是',result.services[i].uuid)
      // wx.setStorageSync('123', result.services[i].uuid)
    that.setData({
      serviceId:result.services[i].uuid
    })
    }
  }
}
 console.log('此时的serciceId是',that.data.serviceId)
 console.log('此时的deviceid是',that.data.deviceId)
var res=await getBLEDeviceCharacteristics(that.data.deviceId,that.data.serviceId)
for(var i=0;i<res.characteristics.length;i++){
  //把特征值id输出到控制台
  console.log("获取到的特征值id:"+res.characteristics[i].uuid)
  if(res.characteristics[i].properties.notify & res.characteristics[i].properties.read){
    console.log("开启notify的characteristicId:"+res.characteristics[i].uuid);
    wx.setStorageSync('124',res.characteristics[i].uuid)
    this.setData({
      notifyCharacteristicId:res.characteristics[i].uuid
    })
  }
  console.log('此时的notifyCharacteristicId',that.data.notifyCharacteristicId)
  if(res.characteristics[i].properties.write & res.characteristics[i].properties.read & res.characteristics[i].properties.notify==false & i<3){
    //因为蓝牙的uuid中可能有多个uuid具有写的功能,不进行过滤的话会导致获取到多个uuid,赋值给write会出现不显示
    //加一个过滤,获取重复元素的第一个
      console.log("开启write的characteristicId:"+res.characteristics[i].uuid);
      wx.setStorageSync('125',res.characteristics[i].uuid)
    this.setData({
      writeCharacteristicId:res.characteristics[i].uuid
    }) 
  }
  // if(res.characteristics[i].properties.read){
  //   console.log("开启read的characteristicId:"+res.characteristics[i].uuid & res.characteristics[i].properties.notify );
  //   this.setData({
  //     readCharacteristicId:res.characteristics[i].uuid
  //   })
  // }
}
console.log('获取读写监听特征值称成功')
console.log('此时的notifyCharacteristicId',that.data.notifyCharacteristicId)
console.log('此时的writeCharacteristicId',that.data.writeCharacteristicId)
// console.log('此时的readCharactersticId',that.data.readCharactersticId)
//9.开启监听
await notifyBLECharacteristicValueChange(that.data.deviceId,that.data.serviceId,that.data.notifyCharacteristicId)
//10.进行监听
wx.onBLECharacteristicValueChange((result) => {
  console.log(result)
  console.log(result.value)
  console.log(buf2string(result.value))
  function buf2string(buffer) {
    var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
    return arr.map((char, i) => {
      return String.fromCharCode(char);
    }).join('');
  } 
})
that.setData({
  showble:false
})
},
sendmessage:function () {
  var that=this;
    console.log('write函数内部的notity',that.data.writeCharacteristicId)
    let model1="$HC12,02"
    console.log(model1)
    let number=that.stringToBytes(model1);//字符转字节
    wx.writeBLECharacteristicValue({
      characteristicId: that.data.writeCharacteristicId,
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      value: number,
      success:(res)=>{
        console.log(res)
      },
      fail:(err)=>{
        console.log(err)
      }
    })

  readBLECharacteristicValue(that.data.writeCharacteristicId,that.data.deviceId,that.data.serviceId);
  console.log('read读取成功')
  
},
test:function () {
  this.sendmessage('1234')
},
ab2hex:function(buffer){
  var hexArr =Array.prototype.map.call(
    new Uint16Array(buffer),
    function(bit){
      return ('00'+bit.toString(16).slice(-2))
    }
  )
  return hexArr.join('');
},
// 字符串转byte
stringToBytes(str) {
  var array = new Uint8Array(str.length);
  for (var i = 0, l = str.length; i < l; i++) {
    array[i] = str.charCodeAt(i);
  }
  console.log(array);
  return array.buffer;
},
//二进制转换为字符串
// ab2str(buf) {
//   return String.fromCharCode.apply(null, new Uint8Array(buf));
// },
ab2str:function(buf){
  return String.fromCharCode.apply(null, new Uint8Array(buf));
},
//ASCII码转16进制
strToHexCharCode:function(str) {
  if (str === "") {
      return "";
  } else {
      var hexCharCode = [];
      hexCharCode.push("0x");
      for (var i = 0; i < str.length; i++) {
          hexCharCode.push((str.charCodeAt(i)).toString(16));
      }
      return hexCharCode.join("");
  }
},
  //弹窗的取消按钮
  onCancel:function(){
    this.setData({
      showble:false,
      showname:true
    })
  },
//蓝牙弹窗的确认键
onConfirm:function () {
  //显示已经连接到的设备名字
  this.setData({
    showble:false
  })
},

// onUnload:function () {
//   wx.closeBluetoothAdapter({
//     success: (res) => {
//      console.log(res);
//     },
//     fail: (err)=>{
//       wx.showToast({
//         title: '数据发送成功,但未关闭蓝牙,请手动关闭',
//         icon:'none'
//       })
//       console.log(err);
//     }
//   })
// }




})


request/lanya.js(这个需要自己新建一个文件夹和文件)

//蓝牙插件
var app = getApp();
  //1.打开蓝牙适配器
  export const openBluetoothAdapter=()=>{
    return new Promise((resolve,reject)=>{
      wx.openBluetoothAdapter({
        success: (result) => {
          resolve(result);
        },
        fail: (err)=>{
          reject(err);
          wx.showToast({
            title: '请打开蓝牙',
            icon: 'none',
            duration:4000
          })
        }
      })
    })
  }
    //2.查看蓝牙适配器状态
  export const getBluetoothAdapterState=()=>{
    return new Promise((resolve,reject)=>{
      wx.getBluetoothAdapterState({
        success: (result) => {
          resolve(result);
        },
        fail: (err)=>{
          wx.showToast({
            title: '请打开蓝牙',
            icon: 'none',
            duration:3000
          })
          reject(err);
        }
      })
    })
  }
    //3.搜索设备
  export const startBluetoothDevicesDiscovery=()=>{
    return new Promise((resolve,reject)=>{
      wx.startBluetoothDevicesDiscovery({
        success: (result) => {
          resolve(result);
        },
        fail: (err)=>{
          wx.showToast({
            title: '搜索设备失败',
            icon: 'none'
          })
          reject(err);
        }
      })
    })
  }
    //4.获取蓝牙设备信息
  export const getBluetoothDevices=()=>{
    return new Promise((resolve,reject)=>{
      wx.getBluetoothDevices({
        success: (result) => {
              //对获取到的设备进行筛选,获取有名字的低功耗蓝牙
              console.log('获取到的蓝牙设备为',result)
              console.log('长度测试',result.devices.length)
              for(var i=0;i<result.devices.length;i++){
                //对蓝牙进行过滤
                if(result.devices[i].name!='未知设备'){
                  console.log('蓝牙名',result.devices[i].name)
                  resolve(result);//打印获取到的蓝牙信息
                }
              }
        },
        fail: (err)=>{
          wx.showToast({
            title: '未获取到设备信息',
            icon: 'none'
          })
          reject(err);
        }
      })
    })
  }
    //5.连接设备
  export const createBLEConnection=(deviceId)=>{
    return new Promise((resolve,reject)=>{
      wx.createBLEConnection({
        deviceId:deviceId,
        success: (result) => {
          console.log(result)
          resolve(result);
          wx.showToast({
            title: '已连接成功',
            icon:'success',
            duration:2000
          })
        },
        fail: (err)=>{
          console.log(err)
          wx.showToast({
            title: '未连接到蓝牙,可能是设备没通电',
            icon: 'none'
          })
          reject(err);
        }
      })
    })
  }
    //6.停止扫描设备
  export const stopBluetoothDevicesDiscovery=()=>{
    return new Promise((resolve,reject)=>{
      wx.stopBluetoothDevicesDiscovery({
        success: (result) => {
          resolve(result);
          console.log('停止扫描设备的函数已启用')
        },
        fail: (err)=>{
          reject(err);
        }
      })
    })
  }
      //7.获取连接设备的service服务
  export const getBLEDeviceServices=(deviceId)=>{
    console.log('已经进入第一层')
    return new Promise((resolve,reject)=>{
      console.log('已经进入第二层')
      wx.getBLEDeviceServices({
        deviceId:deviceId,
        doDiscover:true,
        success: (result) => {
          console.log('已进入第三层')
          console.log("获取到的设备名字是:",result)
          wx.showToast({
            title: '已发现蓝牙设备',
            icon:'success',
            duration:1500
          })
          resolve(result);
        },
        fail: (err)=>{
          wx.showToast({
            title: '未能获取服务',
          })
          reject(err);
          console.log(err)
        }
      })
    })
  }
    //8.获取连接设备具有读写功能服务的所有特征值
  export const getBLEDeviceCharacteristics=(deviceId,serviceId)=>{
    return new Promise((resolve,reject)=>{
      wx.getBLEDeviceCharacteristics({
        deviceId:deviceId,
        serviceId:serviceId,
        success: (result) => {
          resolve(result);
          console.log('获取到的各项特征值为',result)
        },
        fail: (err)=>{
          reject(err);
          console.log(err)
        }
      })
    })
  }
  
    //9.启动蓝牙设备特征值变化
   export const notifyBLECharacteristicValueChange=(deviceId,serviceId,notifyCharacteristicId)=>{
      return new Promise((resolve,reject)=>{
        wx.notifyBLECharacteristicValueChange({
          deviceId:deviceId,
          serviceId:serviceId,
          characteristicId:notifyCharacteristicId,
          state:true,
          success: (result) => {
            resolve(result);
            console.log('开始监听功能',result)
          },
          fail:(err)=>{
            console.log(err)
          }
         
        })
      })
    }
      //10.接受蓝牙发送的数据
      export const onBLECharacteristicValueChange=()=>{
        return new Promise((resolve,reject)=>{
          wx.onBLECharacteristicValueChange({
            // deviceId:deviceId,
            // serviceId:serviceId,
            // characteristicId:notifyCharacteristicId,
            state:true,
            success: (result) => {
              resolve(result);
              console.log('接收蓝牙发送的数据',result)
            },
            fail: (err)=>{
              reject(err);
            }
          })
        })
      }

      //11.向蓝牙写入数据
  export const writeBLECharacteristicValue=(deviceId,serviceId,writeCharacteristicId,value)=>{
    return new Promise((resolve,reject)=>{
      wx.writeBLECharacteristicValue({
        deviceId:deviceId,
        serviceId:serviceId,
        characteristicId:writeCharacteristicId,
        value:value,
        success: (result) => {
          wx.showToast({
            title: '已成功发送数据,蓝牙已打开',
          })
          resolve(result);
        },
        fail: (err)=>{
          reject(err);
          console.log(err)
        }
      })
    })
  }
  //读取低功耗蓝牙的特征值得二进制数值
  export const readBLECharacteristicValue=(writeCharacteristicId, deviceId,serviceId)=>{
    return new Promise((resolve,reject)=>
      wx.readBLECharacteristicValue({
        characteristicId: writeCharacteristicId,
        deviceId: deviceId,
        serviceId: serviceId,
        success:(result)=>{
          console.log('读取低功耗蓝牙的特征值得二进制数值成功')
        },
        fail: (err)=>{
          reject(err);
        }
      })
    )
  }
      //12.关闭蓝牙
  export const closeBluetoothAdapter=()=>{
    return new Promise((resolve,reject)=>{
      wx.closeBluetoothAdapter({
        success: (result) => {
          resolve(result);
        },
        fail: (err)=>{
          wx.showToast({
            title: '数据发送成功,但未关闭蓝牙,请手动关闭',
            icon:'none'
          })
          reject(err);
        }
      })
    })
  }
  function ab2hex(buffer) {
    let hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function(bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  }

  function ab2str(buf) {
    return String.fromCharCode.apply(null, new Uint8Array(buf));
  }


最后附上我做测试的硬件
在这里插入图片描述
ps:我还在wx.getBLEDeviceServices遇到个坑。网上不少教程都是到这一步为止就可以筛选出合适的serviceId,可能因为我用的蓝牙设备是工业级的。所以可供选择的serviceId比较多,我根据我的蓝牙特征用加了一个if再做一个判断。在这里插入图片描述
最后附上我的qq:3233456044.有问题可以相互交流
我所用的蓝牙插件来自另外一个博主:
我用#优快云#这个app发现了有技术含量的博客,小伙伴们求同去《微信小程序连接蓝牙模块发送数据的详解以及封装版》, 一起来围观吧 https://blog.youkuaiyun.com/weixin_51375107/article/details/116009436?utm_source=app&app_version=4.11.0&code=app_1562916241&uLinkId=usr1mkqgl919blen

评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值