微信蓝牙小程序,连接蓝牙模块收发数据。遇到的问题:我连接成功之后发现服务值下面两个特征值一个只能读一个只能写,然后点击读的那个一直收到同一个字,点击发送无论发什么内容只能收到同一个中文字,求指导

大家好,我是小程序初学者,目前尝试做一个蓝牙小程序连接蓝牙模块进行收发数据,遇到了问题求大佬指点

微信蓝牙小程序,连接蓝牙模块收发数据。遇到的问题:我连接成功之后发现服务值下面两个特征值一个只能读一个只能写,然后点击读的那个一直收到同一个字,点击发送无论发什么内容只能收到同一个中文字,求指导

微信蓝牙小程序,连接蓝牙模块收发数据。遇到的问题:我连接成功之后发现服务值下面两个特征值一个只能读一个只能写,然后点击读的那个一直收到同一个字,点击发送无论发什么内容只能收到同一个中文字,求指导

微信蓝牙小程序,连接蓝牙模块收发数据。遇到的问题:我连接成功之后发现服务值下面两个特征值一个只能读一个只能写,然后点击读的那个一直收到同一个字,点击发送无论发什么内容只能收到同一个中文字,求指导

这是代码运行结果:点击能读的特征值就会接收到耀这个字,点击输入框无论发送什么都会接收到肀这个字


遇到的问题:我连接成功之后发现服务值下面两个特征值一个只能读一个只能写,然后点击读的那个一直收到同一个字,点击发送无论发什么内容只能收到同一个中文字,我在想是需要将两个特征值合在一起使用吗?求指导(ps:小程序是跟着b站上面一个博主做的,他是想把手机发送的内容显示到手机上的接受区,我想实现手机发送在串口助手显示,串口助手发送的能在手机小程序接收区显示),以下是代码内容lanya.wxml部分





                                                               
    {{device.name}} {{device.deviceId}}
    

蓝牙设备:{{name}} {{deviceId}}
点击下面服务值获得特征值



    
        服务值:{{service.uuid}}


点击下面特征值读写数据


        特征值:{{characteristic.uuid}}  read:{{characteristic.properties.read}} write:{{characteristic.properties.write}}




请输入数据:



接收到的数据: 
{{showData}}


lanya.js部分:

//将接收到的字符转化为我们发送的数据
function ab2str(buf){
  return String.fromCharCode.apply(null,new Uint16Array(buf));
}
//定义一个全局变量
let revData = ''
Page({

  /**
   * 页面的初始数据
   */
  data: {
      discoverFlag:false,
      devices:[],
      deviceId:'',//蓝牙设备id
      serviceId:'',//蓝牙特征对应服务的UUID


      services:[],
      characteristics:[],//特征值的列表
      characteristicId:'',//蓝牙特征的UUID
      showFlage:true,
      name:'',//保存设备的名字
      showFlage1:false,
      showFlage2:false,

      available:true,
      read:false,
      write:false,
      showKeyboard:false,
      inputKey:true,//设置刚开始输入框不起作用,等到点击特征值之后再起作用
      showData:'',
  },

  /**
   * 生命周期函数--监听页面加载
   * 初始化蓝牙模块
   */
  onLoad: function (options) {
    wx.getBluetoothAdapterState({
      success(res){
        console.log(res)
        if(res.available){
          that.setData({
            available:true
          })
        } else{
          that.setData({
            available:false
          })
        }
      }
    })
    if(this.data.available==false){
      wx.showToast({
        title: '请打开蓝牙',
      })
    }
      wx.openBluetoothAdapter({
        success (res) {
          console.log(res)
        }
      })
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
      wx.getBluetoothAdapterState({
        success (res) {
          console.log(res)
          
            if(res.available){
              // wx:wx.showToast({
                // title: '蓝牙没有打开',
                that.setData({
                  available:true
                })
            }else{
              that.setData({
                available:false
              })
              
            }
        }
      })
      if(this.data.available==false){
          wx.showToast({
            title: '请打开蓝牙',
          })
      }
      wx.openBluetoothAdapter({
        success (res) {
          console.log(res)
        }
      })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  },
  // 初始化蓝牙模块,切记打开蓝牙
  openAdapter(e){
    wx.openBluetoothAdapter({
      success (res) {
        console.log(res)
      }
    })
  },

//搜寻附近蓝牙设备
  getDevices(){
    let that = this
  // 开始监听蓝牙设备之前,先判断discoverflag是不是真的开始搜寻了
  // getDevices(){
  //   let that = this
    wx.startBluetoothDevicesDiscovery({
      services: [],
      success (res) {
        console.log(res)

        function ab2hex(buffer) {
          var hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function(bit) {
              return ('00' + bit.toString(16)).slice(-2)
            }
          )
          return hexArr.join('');
        }
        // 可以搜寻蓝牙设备ok的话这里放置一个标志
        // that.setData({
        //   // 把这个值放在里面,如果他能搜到的话,方便后面使用
        //   discoverFlag:res.isDiscovering
        // })
     
    // 这里要注意先定义discoverflag
    // if(this.data.discoverFlag){
      // ArrayBuffer转16进度字符串示例
      // 监听搜索到蓝牙设备,将新设备一一列出来
      wx.onBluetoothDeviceFound(function(res) {
          console.log(res)
          let devices = res.devices;

          console.log('new device list has founded')
          // console.dir(devices)//打印设备信息,报错不要紧
          console.log(ab2hex(devices[0].advertisData))

          // ArrayBuffer转16进度字符串示例
          wx.getBluetoothDevices({
            success: function (res) {
              console.log(res)
              that.setData({
                devices:res.devices
              })
            }
          })
          //停止搜寻附近的蓝牙外围设备,如果搜寻到四个设备以上就暂停
          if(that.data.devices.length >= 4){
            wx.stopBluetoothDevicesDiscovery({
              success (res) {
                console.log(res)
              }
            })
          }

      })
    // }
        //如果第一个不是空的的话就打印出来,没有必要可以去掉
    }
  })
},
  //连接蓝牙设备
  create(e){
    let that = this
    console.log(e)
    // 将索引放到index里面
    let index = e.currentTarget.dataset.index
    //获取本机蓝牙适配器状态
    wx.getBluetoothAdapterState({
      success (res) {
        console.log(res)
          if(res.available){
            that.setData({
              available:true
            })
          } else {
            that.setData({
              available:false
            })
          }
      }
    })
    if(this.data.available == false){
      wx.showToast({
        title: '请打开蓝牙',
      })
    }

    wx.createBLEConnection({
      deviceId:that.data.devices[index].deviceId,//点击的那条就取哪条
      wx: wx.showLoading({
        title: '连接中',
      }),

      success (res) {
        console.log(res)//成功回调打印出来
        that.setData({
          deviceId:that.data.devices[index].deviceId,//把数据的值存到这里
          name:that.data.devices[index].name,
          showFlage:false,
          showFlage1:true
        })
          //提示连接成功
          wx:wx.hideLoading({
              // title:'已连接',
          })
        // 获取蓝牙低功耗设备所有服务
        wx.getBLEDeviceServices({
          // 这里的 deviceId 需要已经通过 wx.createBLEConnection 与对应设备建立连接
          deviceId:that.data.deviceId,
          success (res) {
            console.log('device services:', res.services)
            //把列表取出来,一定要加this.setData
            that.setData({
              services:res.services
            })  
          }
        })
      }
    })
  },
  // 判定点击的是哪个服务值
  choise(e){
      console.log(e)
      let that = this
      let index = e.currentTarget.dataset.index
      let serviceId = this.data.services[index].uuid

      this.setData({
        serviceId:serviceId,
      })
    // 获取蓝牙低功耗设备某个服务中所有特征
    wx.getBLEDeviceCharacteristics({
        // 这里的 deviceId 需要已经通过 wx.createBLEConnection 与对应设备建立链接
        deviceId:this.data.deviceId,
        // 这里的 serviceId 需要在 wx.getBLEDeviceServices 接口中获取
        serviceId: this.data.serviceId,//成功回调后获得特征值
        success (res) {
          console.log('device getBLEDeviceCharacteristics:', res.characteristics)
          that.setData({
            characteristics:res.characteristics,
            showFlage2:true,
            showFlage1:false,
          })
        }
    })
  },
  disconnect(){
    let that = this
      wx.closeBLEConnection({
        deviceId:this.data.deviceId,
        success (res) {
          console.log(res)
          that.setData({
            showFlage:true,
            showFlage1:false,
            showFlage2:false,
            inputKey:true,//当点击断开连接返回时,输入框禁用状态
          })
        }
      })
  },
  select(e){
    let that = this
    console.log(e)
    // 将index读取出来,index就是点击了哪个特征值
    let index = e.currentTarget.dataset.index
    // 这个id就等于当前数据里面特征值列表,取出来以后放到初始数据里面
    let characteristicId = this.data.characteristics[index].uuid
    // 将获得的特征值数据放入初始数据里面
    this.setData({
      characteristicId:characteristicId,
      // 设置点击特征值之后,输入框才启用
      showKeyboard:true,
      inputKey:false,//当一点击某个特征值就会往里面的写数据变为false

    })
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
      deviceId:this.data.deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId:this.data.serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId:this.data.characteristicId,
      success (res) {
        console.log('notifyBLECharacteristicValueChange success', res.errMsg)
        // ArrayBuffer转16进制字符串示例
        function ab2hex(buffer) {
          let hexArr = Array.prototype.map.call(
            new Uint8Array(buffer),
            function(bit) {
              return ('00' + bit.toString(16)).slice(-2)
            }
          )
          return hexArr.join('');
        }
        //监听变化
        wx.onBLECharacteristicValueChange(function(res) {
          console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
          console.log('ArrayBuffer转16进制字符串',ab2hex(res.value))
          var resValue = new Uint8Array(res.value,0);
          console.log('ArrayBuffer转Uint8Array',resValue)
          console.log(ab2hex(res.value))
          console.log(ab2str(res.value))//利用这个方法将接收到的字符转化过来
          let value = ab2str(res.value)
          // 为了防止后面的值覆盖前面接受到的值,需要定义一个全局变量
          //将值累加起来,不让覆盖
          revData += value
          //设置叠加是有限的,不能无底线叠加,意思是清空之前叠加的数据,将最后叠加后的数据赋值给他
          if(revData.length>=30){
            revData = value
          }
          that.setData({
            showData: revData
           
          })
        })
      }
    })
  },
  sendData(e){
    console.log(e)
    //将输入的值给取出来
    let value = e.detail.value
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(value.length)//改成输入这串字符的长度
    let dataView = new DataView(buffer)
    //设置一个循环,一个一个字符来处理,因为我们可能不止发送一个值
    for(let i = 0;i < value.length;i++){
    dataView.setUint8(i, value[i].charCodeAt())//字符转换成Ascii码
    }
    dataView.setUint8(0, 0)

    wx.writeBLECharacteristicValue({
      // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
      deviceId:this.data.deviceId,
      // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
      serviceId:this.data.serviceId,
      // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
      characteristicId:this.data.characteristicId,
      // 这里的value是ArrayBuffer类型
      value: buffer,
      
      success (res) {
        // 将发送的数据打印出来
        console.log(buffer)
        console.log('writeBLECharacteristicValue success', res.errMsg)
        wx.showToast({
          title: '发送成功',
        })
      },
      fail(res){
        wx.showToast({
          title: '发送失败',
        })
      }
    })
  }
})

 

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/7aa22a8965.html