uniapp 蓝牙数据交互demo代码
时间: 2023-08-11 15:03:43 浏览: 151
uniapp蓝牙封装.zip
5星 · 资源好评率100%
以下是一个简单的UniApp蓝牙数据交互demo代码,仅供参考:
```
<template>
<div>
<button @click="sendMsg">发送消息</button>
<button @click="receiveMsg">接收消息</button>
<textarea v-model="msg"></textarea>
</div>
</template>
<script>
export default {
data() {
return {
msg: '', // 发送的消息
connectedDeviceId: '', // 已连接设备Id
serviceId: '', // 服务Id
characteristicId: '', // 特征值Id
}
},
methods: {
// 发送消息
sendMsg() {
uni.writeBLECharacteristicValue({
deviceId: this.connectedDeviceId,
serviceId: this.serviceId,
characteristicId: this.characteristicId,
value: this.msg,
success: res => {
console.log(res)
},
fail: err => {
console.error(err)
}
})
},
// 接收消息
receiveMsg() {
uni.onBLECharacteristicValueChange(res => {
console.log(res)
console.log(this.ab2str(res.value))
})
uni.notifyBLECharacteristicValueChanged({
state: true,
deviceId: this.connectedDeviceId,
serviceId: this.serviceId,
characteristicId: this.characteristicId,
success: res => {
console.log(res)
},
fail: err => {
console.error(err)
}
})
},
// ArrayBuffer转字符串
ab2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf))
},
},
onShow() {
// 获取已连接设备Id、服务Id、特征值Id等信息
uni.getConnectedBluetoothDevices({
success: res => {
console.log(res)
this.connectedDeviceId = res.devices[0].deviceId
uni.getBLEDeviceServices({
deviceId: this.connectedDeviceId,
success: res => {
console.log(res)
this.serviceId = res.services[0].uuid
uni.getBLEDeviceCharacteristics({
deviceId: this.connectedDeviceId,
serviceId: this.serviceId,
success: res => {
console.log(res)
this.characteristicId = res.characteristics[0].uuid
},
fail: err => {
console.error(err)
}
})
},
fail: err => {
console.error(err)
}
})
},
fail: err => {
console.error(err)
}
})
},
}
</script>
```
以上代码实现了基本的蓝牙数据发送、接收等功能,但仅仅是一个demo,实际使用时需要根据具体需求进行修改。需要注意的是,蓝牙操作涉及到很多异步回调,需要仔细处理回调的顺序和逻辑。
阅读全文