小程序连蓝牙,发送数据

32 篇文章 1 订阅
1 篇文章 0 订阅
<template>
  <div class="bluetooth">
    蓝牙
  </div>
</template>


<script>
  // import 'weui-wxss'
  export default {
    data () {
      return {
       
        sendData: 'ACAD06A000000008BCBD',
		deviceId:'',
		tip:'',
		data:{
		  discover:''
		}
      }
    },
	methods:{
	    openBluetoothAdapter() {
	      let that = this
	      wx.openBluetoothAdapter({
	        success: (res) => {
	          console.log('openBluetoothAdapter success', res)
	          that.startBluetoothDevicesDiscovery()
	        },
	        fail: (res) => {
	          console.log('res', res)
	          // if (res.errCode === 10001) {
	          wx.showModal({
	            // title: '蓝牙',
	            content: '请开启蓝牙,部分安卓机需要开启定位服务',
	            showCancel: false
	          })
	          wx.onBluetoothAdapterStateChange(function (res) {
	            console.log('onBluetoothAdapterStateChange', res)
	            if (res.available) {
	              that.startBluetoothDevicesDiscovery()
	            }
	          })
	          // }
	        }
	      })
	    },
	    startBluetoothDevicesDiscovery() {
	      let that = this
	      if (this.data.discover) {
	        return
	      }
	      this.data.discover = true
	      wx.startBluetoothDevicesDiscovery({
	        allowDuplicatesKey: true,
	        success: (res) => {
	          console.log('startBluetoothDevicesDiscovery success', res)
	          that.onBluetoothDeviceFound()
	        },
	        fail: (res) => {
	          console.log('startBluetoothDevicesDiscovery fail', res)
	        }
	      })
	    },
	    onBluetoothDeviceFound() {
	      let that = this
	      wx.onBluetoothDeviceFound((res) => {
	        console.log('onBluetoothDeviceFound', res)
	        res.devices.forEach(device => {
	          if (!device.name && !device.localName) {
	            return
	          }
	          console.log(device.name)
	          if (device.name.indexOf('FitRx Wireless') !== -1) {
	              that.deviceId = device.deviceId
	            that.createBLEConnection(device);
	          }
	          
	        })
	      })
	    },
	    restartBLE(){
	      if(!this.deviceId){
	        setTimeout(function(){
	          wx.showModal({
	            title:'提示',
	            content:'蓝牙连接失败,请重新新增检查',
	            showCancel:false,
	            success(res){
	              if (res.confirm) {
	                console.log('用户点击确定')
	                wx.navigateBack()
	              } else if (res.cancel) {
	                console.log('用户点击取消')
	              }
	            }
	          })
	        },30000)
	      }
	    },
	    createBLEConnection(ds) {
	      // const ds = e.currentTarget.dataset
	      const deviceId = ds.deviceId
	      const name = ds.name
	      let that = this
		  console.log(deviceId,'aaaaaaaaaaa')
		  console.log(name,'bbbbbbbbbb')
		  wx.showLoading({
		    title: '连接蓝牙设备中...'
		  })
	      wx.createBLEConnection({
	        deviceId: deviceId,
	        success: (res) => {
				console.log(res,'bbccccc')
				wx.hideLoading()
				wx.stopBluetoothDevicesDiscovery({
				  success: function (res) {
				    // that.searchDevice = !that.searchDevice
				    console.log('关闭蓝牙设备搜索')
				  }
				})
	          // that.setData({
	            // that.tip = '设备连接中,请稍等...',
	            // name,
	            // deviceId,
	          // })
	          // if (that.data.platform === 'android') {
	          //   that.setBLEMTU(deviceId)
	          // } else {
	            that.getBLEDeviceServices(deviceId)
	          // }
	        },
	        fail: (res) => {
			  this.restartBLE()
	          console.log('createBLEConnection fail', res)
	        }
	      })
	      that.stopBluetoothDevicesDiscovery()
	    },
	    stopBluetoothDevicesDiscovery() {
	      wx.stopBluetoothDevicesDiscovery()
	    },
	    getBLEDeviceServices(deviceId) {
	      let that = this
	      wx.getBLEDeviceServices({
	        deviceId,
	        success: (res) => {
	          console.log('getBLEDeviceServices', res)
	          let service = res.services.find(item => (item.uuid).toUpperCase().indexOf('AE3A') !== -1)
	          if (service) {
	            that.getBLEDeviceCharacteristics(deviceId, service.uuid)
	          }
	        },
	        fail: (res) => {
	          console.log('getBLEDeviceServices fail', res)
	        }
	      })
	    },
	    // ArrayBuffer转16进度字符串示例
	    ab2hex(buffer) {
	      var hexArr = Array.prototype.map.call(
	        new Uint8Array(buffer),
	        function (bit) {
			
	          return ('00' + bit.toString(16)).slice(-2)
	        }
	      )
	      return hexArr.join('');
	    },
	    hextoString(hex) {
	      var arr = hex.split("")
	      var out = ""
	      for (var i = 0; i < arr.length / 2; i++) {
			  console.log( arr[i * 2] + arr[i * 2 + 1],'string')
	        var tmp = Number("0x" + arr[i * 2] + arr[i * 2 + 1])
	        var charValue = tmp.toString()
			// String.fromCharCode(tmp);
			console.log(tmp,'tmpppppppppppp')
			console.log(charValue,'charValueppppppppppp')
	        out += charValue
	      }
	      return out
	    },
	    getBLEDeviceCharacteristics(deviceId, serviceId) {
			console.log(deviceId,'============')
			console.log(serviceId,'pppppppppppp')
	      var that = this
	      let characteristicId = null
	      wx.getBLEDeviceCharacteristics({
	        deviceId,
	        serviceId,
	        success: (res) => {
	          // console.log('getBLEDeviceCharacteristics success', res.characteristics)
	          let characteristic = res.characteristics.find(item => (item.uuid).toUpperCase().indexOf('AE3C') !== -1)
			  let characteristicaa = res.characteristics.find(item => (item.uuid).toUpperCase().indexOf('AE3B') !== -1)
	          // that.setData({
	          wx.showLoading({
	            title: '数据传输中...'
	          })
	  
	          // })
	          characteristicId = characteristic.uuid
			  characteristicaa = characteristicaa.uuid
			  
	          wx.notifyBLECharacteristicValueChange({
	            deviceId,
	            serviceId,
	            characteristicId,
	            state: true,
	            success: function (res) {
	              console.log('notify success', res.errMsg)
				  var hex = 'ACAD06A000000007BCBD'
				  // let dataArray = hex.split(' ')
				  // let dataBuffer = new ArrayBuffer(hex.length)
				  // let dataView = new DataView(dataBuffer)
				  // for (let j = 0; j < dataArray.length; j++) {
				  // 	dataView.setUint8(j, Number('0x'+hex[j]))
				  //  }
				   var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
				        return parseInt(h, 16)
				    }))
				   var dataBuffer = typedArray.buffer
				   
				   // var buffer1 = new ArrayBuffer(typedArray)
				  wx.writeBLECharacteristicValue({
				    deviceId: deviceId,
				    serviceId: serviceId,
				    characteristicId: characteristicaa,
				    value: dataBuffer,
				    success: function (res) {
					  wx.hideLoading()
				      console.log('message发送成功',res)
				      wx.showModal({
				        title: '数据发送成功'
				      })
				      wx.readBLECharacteristicValue({
				        deviceId: deviceId,
				        serviceId: serviceId,
				        characteristicId: characteristicId,
				        success: function (res) {
				          console.log('读取数据成功')
				        }
				      })
				    },
				    fail: function (res) {
				  	  console.log(res)
				      // fail
				      console.log('message发送失败')
				      wx.showToast({
				        title: '数据发送失败,请稍后重试',
				        icon: 'none'
				      })
				    },
				    complete: function (res) {
				      // fail
				      console.log('message发送完成')
				    }
				  })
	            },
	            fail: function (res) {
	              console.log('notify fail', res.errMsg)
	            },
	            complete: function (res) {
	              console.log('notify complete', res.errMsg)
	            },
	          })
	        },
	        fail(res) {
	          console.error('getBLEDeviceCharacteristics', res)
	        }
	      })
	      // 操作之前先监听,保证第一时间获取数据
		  // ArrayBuffer转为字符串,参数为ArrayBuffer对象
	      wx.onBLECharacteristicValueChange((characteristic) => {
	        console.log('value', characteristic.value)
	        let data = that.blData

	        let blData = that.hextoString(that.ab2hex(characteristic.value))
	        console.log('blData', blData)
	        setTimeout(function(){
	          console.log('-------',blData)
	          if(!blData){
	            if(data.indexOf('AE3B')!==-1){
	              // xxx 处理数据
	            }
	          }
	        },3000)
	        if (that.blData) {
	          // that.setData({
	            that.blData = data.concat(blData)
	          // })
	        } else {
	          // that.setData({
	            that.blData = that.blData
	          // })
	        }
	        that.blData=null
	      })
	    }
		},
	    // closeBLEConnection() {
	    //   wx.closeBLEConnection({
	    //     deviceId: this.deviceId
	    //   })
	    // },
	    closeBluetoothAdapter() {
	      wx.closeBluetoothAdapter()
	      this.data.discover = false
	    },
	    onLoad(){
	      this.openBluetoothAdapter()
	    },
	    onUnload(){
	      this.stopBluetoothDevicesDiscovery()
	      // this.closeBLEConnection()】】】、
	      this.closeBluetoothAdapter()
	    }
  
    
  }
</script>

<style scoped>

  .status {
    background-color: white;
    height: 50px;
    display: flex;
    align-items: center;
    flex-direction: row;
    border-bottom: 2px solid #e8e8e8;
  }
  .status-text {
    margin-left:10px;
    font-size: 15px;
    width:40%
  }

  .status-text1 {
    height:30px;
    background-color:#e8e8e8;
    margin-left:10px;
    font-size: 13px;
    border-radius: 15px;
    margin-top: 5px;
    width: 50%;
    text-align: center;
    line-height: 30px;
    color: black;
  }

  .switch {
    margin-left:10px;
    width: 50%;
    text-align: center;
  }

  .devices {
    display: flex;
    align-items: center;
    flex-direction: column;
  }

  .device-list {
    margin-top: 15px;
    font-size: 3px;
    border: 3px solid #e8e8e8;
    border-radius: 15px;
    width: 94%;
  }

  .inputMessage {
    text-align: center;
    font-size: 13px;
  }
</style>


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值