大家好,我是小程序初學者,目前嘗試做一個藍牙小程序連接藍牙模塊進行收發(fā)數(shù)據(jù),遇到了問題求大佬指點
這是代碼運行結(jié)果:點擊能讀的特征值就會接收到耀這個字,點擊輸入框無論發(fā)送什么都會接收到肀這個字
遇到的問題:我連接成功之后發(fā)現(xiàn)服務值下面兩個特征值一個只能讀一個只能寫,然后點擊讀的那個一直收到同一個字,點擊發(fā)送無論發(fā)什么內(nèi)容只能收到同一個中文字,我在想是需要將兩個特征值合在一起使用嗎?求指導(ps:小程序是跟著b站上面一個博主做的,他是想把手機發(fā)送的內(nèi)容顯示到手機上的接受區(qū),我想實現(xiàn)手機發(fā)送在串口助手顯示,串口助手發(fā)送的能在手機小程序接收區(qū)顯示),以下是代碼內(nèi)容lanya.wxml部分
<!-- <button bindtap="openAdapter">初始化藍牙模塊</button> -->
<!-- <button bindtap="discoverDevices">開始搜尋附近的藍牙設備</button> -->
<button bindtap="getDevices">獲得周邊藍牙設備</button>
<!-- 一個一個遍歷準備連接設備:點擊設備名稱即可鏈接 -->
<view wx:if="{{showFlage}}" wx:for="{{devices}}" wx:for-item="device" wx:key="key" bindtap="create" data-index="{{index}}">
<view style="width: 750rpx;height:100rpx;color:gray;">{{device.name}} {{device.deviceId}}
</view>
</view>
<view wx:if="{{showFlage1}}">藍牙設備:{{name}} {{deviceId}}</view>
<view wx:if="{{showFlage1}}">點擊下面服務值獲得特征值</view>
<!-- 判斷是哪個服務值像之前判斷是哪個藍牙設備那樣 -->
<view wx:for="{{services}}" wx:for-item="service" wx:key="key" bindtap="choise" data-index="{{index}}">
<!-- 將它遍歷出來,把id提出來-->
<view wx:if="{{showFlage1}}" style="color: hotpink;">服務值:{{service.uuid}}</view>
</view>
<view wx:if="{{showFlage2}}">點擊下面特征值讀寫數(shù)據(jù)</view>
<!-- 一個服務值里面有好多特征值,需要數(shù)據(jù)索引,添加點擊事件 -->
<view wx:if="{{showFlage2}}" style="color: blue;" wx:for="{{characteristics}}" wx:for-item="characteristic" wx:key="key" bindtap="select"data-index="{{index}}">
<view>特征值:{{characteristic.uuid}} read:{{characteristic.properties.read}} write:{{characteristic.properties.write}}</view>
</view>
<button bindtap="disconnect">斷開連接并返回</button>
<!-- 在輸入框上面寫入提示 -->
<view style="background-color: lightgray;">請輸入數(shù)據(jù):
<!-- 設置不能剛進入小程序就顯示能夠輸入數(shù)據(jù),利用showkeyboard來設置,改變鍵盤發(fā)送按鍵,并在點擊完成時觸發(fā)-->
<input style="height: 100rpx;width: 750rpx;" focus = "{{showKeyboard}}" confirm-type="send" bindconfirm="sendData" disabled="{{inputKey}}"></input>
</view>
<view>接收到的數(shù)據(jù):</view>
<view>{{showData}}</view>
lanya.js部分:文章來源:http://www.zghlxwxcb.cn/news/detail-792028.html
//將接收到的字符轉(zhuǎn)化為我們發(fā)送的數(shù)據(jù)
function ab2str(buf){
return String.fromCharCode.apply(null,new Uint16Array(buf));
}
//定義一個全局變量
let revData = ''
Page({
/**
* 頁面的初始數(shù)據(jù)
*/
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:'',
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面加載
* 初始化藍牙模塊
*/
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)
}
})
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面顯示
*/
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)
}
})
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面隱藏
*/
onHide: function () {
},
/**
* 生命周期函數(shù)--監(jiān)聽頁面卸載
*/
onUnload: function () {
},
/**
* 頁面相關事件處理函數(shù)--監(jiān)聽用戶下拉動作
*/
onPullDownRefresh: function () {
},
/**
* 頁面上拉觸底事件的處理函數(shù)
*/
onReachBottom: function () {
},
/**
* 用戶點擊右上角分享
*/
onShareAppMessage: function () {
},
// 初始化藍牙模塊,切記打開藍牙
openAdapter(e){
wx.openBluetoothAdapter({
success (res) {
console.log(res)
}
})
},
//搜尋附近藍牙設備
getDevices(){
let that = this
// 開始監(jiān)聽藍牙設備之前,先判斷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轉(zhuǎn)16進度字符串示例
// 監(jiān)聽搜索到藍牙設備,將新設備一一列出來
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轉(zhuǎn)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
//獲取本機藍牙適配器狀態(tài)
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)//成功回調(diào)打印出來
that.setData({
deviceId:that.data.devices[index].deviceId,//把數(shù)據(jù)的值存到這里
name:that.data.devices[index].name,
showFlage:false,
showFlage1:true
})
//提示連接成功
wx:wx.hideLoading({
// title:'已連接',
})
// 獲取藍牙低功耗設備所有服務
wx.getBLEDeviceServices({
// 這里的 deviceId 需要已經(jīng)通過 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 需要已經(jīng)通過 wx.createBLEConnection 與對應設備建立鏈接
deviceId:this.data.deviceId,
// 這里的 serviceId 需要在 wx.getBLEDeviceServices 接口中獲取
serviceId: this.data.serviceId,//成功回調(diào)后獲得特征值
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,//當點擊斷開連接返回時,輸入框禁用狀態(tài)
})
}
})
},
select(e){
let that = this
console.log(e)
// 將index讀取出來,index就是點擊了哪個特征值
let index = e.currentTarget.dataset.index
// 這個id就等于當前數(shù)據(jù)里面特征值列表,取出來以后放到初始數(shù)據(jù)里面
let characteristicId = this.data.characteristics[index].uuid
// 將獲得的特征值數(shù)據(jù)放入初始數(shù)據(jù)里面
this.setData({
characteristicId:characteristicId,
// 設置點擊特征值之后,輸入框才啟用
showKeyboard:true,
inputKey:false,//當一點擊某個特征值就會往里面的寫數(shù)據(jù)變?yōu)閒alse
})
wx.notifyBLECharacteristicValueChange({
state: true, // 啟用 notify 功能
// 這里的 deviceId 需要已經(jīng)通過 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轉(zhuǎn)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('');
}
//監(jiān)聽變化
wx.onBLECharacteristicValueChange(function(res) {
console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
console.log('ArrayBuffer轉(zhuǎn)16進制字符串',ab2hex(res.value))
var resValue = new Uint8Array(res.value,0);
console.log('ArrayBuffer轉(zhuǎn)Uint8Array',resValue)
console.log(ab2hex(res.value))
console.log(ab2str(res.value))//利用這個方法將接收到的字符轉(zhuǎn)化過來
let value = ab2str(res.value)
// 為了防止后面的值覆蓋前面接受到的值,需要定義一個全局變量
//將值累加起來,不讓覆蓋
revData += value
//設置疊加是有限的,不能無底線疊加,意思是清空之前疊加的數(shù)據(jù),將最后疊加后的數(shù)據(jù)賦值給他
if(revData.length>=30){
revData = value
}
that.setData({
showData: revData
})
})
}
})
},
sendData(e){
console.log(e)
//將輸入的值給取出來
let value = e.detail.value
// 向藍牙設備發(fā)送一個0x00的16進制數(shù)據(jù)
let buffer = new ArrayBuffer(value.length)//改成輸入這串字符的長度
let dataView = new DataView(buffer)
//設置一個循環(huán),一個一個字符來處理,因為我們可能不止發(fā)送一個值
for(let i = 0;i < value.length;i++){
dataView.setUint8(i, value[i].charCodeAt())//字符轉(zhuǎn)換成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) {
// 將發(fā)送的數(shù)據(jù)打印出來
console.log(buffer)
console.log('writeBLECharacteristicValue success', res.errMsg)
wx.showToast({
title: '發(fā)送成功',
})
},
fail(res){
wx.showToast({
title: '發(fā)送失敗',
})
}
})
}
})
?文章來源地址http://www.zghlxwxcb.cn/news/detail-792028.html
到了這里,關于微信藍牙小程序,連接藍牙模塊收發(fā)數(shù)據(jù)。遇到的問題:我連接成功之后發(fā)現(xiàn)服務值下面兩個特征值一個只能讀一個只能寫,然后點擊讀的那個一直收到同一個字,點擊發(fā)送無論發(fā)什么內(nèi)容只能收到同一個中文字,求指導的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!