<template>
<div>
<view class="">
<view class="">
蓝牙 :{{deviceId}}
</view>
<view class="">
服务 :{{fuwu_uuid}}
</view>
</view>
<button type="default" @click="openBluetoothAdapter">1.初始化蓝牙模块</button>
<button type="default" @click="startBluetoothDevicesDiscovery">2.开始搜寻附近的蓝牙外围设备</button>
<button type="default" @click="stopBluetoothDevicesDiscovery">停止搜寻附近的蓝牙外围设备</button>
<button type="default" @click="getConnectedBluetoothDevices">根据 uuid 获取处于已连接状态的设备</button>
<button type="default" @click="closeBLEConnection">断开与低功耗蓝牙设备的连接</button>
<button type="default" @click="getBLEDeviceServices" v-if="deviceId">3.获取蓝牙设备所有服务</button>
<scroll-view scroll-y="true" class="list_box">
蓝牙列表
<view v-for="(item,index) in list" :key="index">
<text>蓝牙设备名称:{{item.name}};</text>
<text>设备的id:{{item.deviceId}};</text>
<text>信号强度:{{item.RSSI}};</text>
<button size="mini" @click="createBLEConnection(item)">连接蓝牙设备</button>
</view>
</scroll-view>
<view class="">
<input type="text" v-model="text_val" style="background-color: red;">
<button size="mini" @click="writeBLECharacteristicValue">写入</button>
<button size="mini" @click="readBLECharacteristicValue(tezheng_uuid)">读取</button>
</view>
</div>
</template>
<script>
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
(bit) => {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
}
function ab2Str(arrayBuffer) {
let unit8Arr = new Uint8Array(arrayBuffer);
let encodedString = String.fromCharCode.apply(null, unit8Arr);
return encodedString
}
export default {
data() {
return {
// 蓝牙
list: [],
deviceId: "",
// 服务
services: [],
fuwu_uuid: "",
// 特征
characteristics: [],
tezheng_uuid: "",
//
text_val: "",
}
},
onLoad() {
// this.openBluetoothAdapter()
},
methods: {
// 初始化蓝牙模块
openBluetoothAdapter() {
uni.openBluetoothAdapter({
success(res) {
uni.showToast({
title: "初始化成功",
})
},
fail: (err) => {
console.log(22, err)
uni.showModal({
title: "初始化失败",
content: err.errMsg
})
}
})
},
// 开始搜寻附近的蓝牙外围设备
startBluetoothDevicesDiscovery() {
let that = this
uni.startBluetoothDevicesDiscovery({
success(res) {
uni.showToast({
title: "成功",
})
that.onBluetoothDeviceFound()
},
fail: (err) => {
console.log(22, err)
uni.showToast({
title: "失败",
icon: "none"
})
}
})
},
// 监听寻找到新设备的事件
onBluetoothDeviceFound() {
uni.onBluetoothDeviceFound((devices) => {
console.log(JSON.parse(JSON.stringify(devices.devices[0])))
devices.devices[0].rui_ab2hex = ab2hex(devices.devices[0].advertisData)
this.list = this.list.concat(devices.devices)
// console.log(ab2hex(devices.devices[0].advertisData))
})
},
// 停止搜寻附近的蓝牙外围设备
stopBluetoothDevicesDiscovery() {
uni.stopBluetoothDevicesDiscovery({
success(res) {
uni.showToast({
title: "成功",
})
},
fail: (err) => {
uni.showToast({
title: "失败",
icon: "none"
})
}
})
},
// 连接蓝牙设备
createBLEConnection(item) {
let deviceId = item.deviceId
uni.createBLEConnection({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId,
success: (res) => {
uni.showToast({
title: "连接成功",
})
console.log(res, deviceId)
this.deviceId = deviceId
// 自动获取
this.getBLEDeviceServices()
},
fail: (err) => {
console.log(22, err)
uni.showToast({
title: "连接失败",
icon: "none"
})
}
})
},
// 根据 uuid 获取处于已连接状态的设备
getConnectedBluetoothDevices() {
uni.getConnectedBluetoothDevices({
services: this.list,
success: (res) => {
console.log(11, res)
},
fail: (err) => {
console.log(22, err)
uni.showToast({
title: "获取失败",
icon: "none"
})
}
})
},
// 断开与低功耗蓝牙设备的连接
closeBLEConnection() {
uni.closeBLEConnection({
deviceId: "",
success(res) {
console.log(res)
}
})
},
// 获取蓝牙设备所有服务(service)
getBLEDeviceServices() {
uni.getBLEDeviceServices({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: this.deviceId,
success: (res) => {
console.log('获取蓝牙设备所有服务:', res)
res.services = res.services || []
this.services = res.services
res.services.forEach(v => {
if (v.uuid == "0000FFE0-0000-1000-8000-00805F9B34FB") {
console.log("自动获取特征", v)
this.fuwu_uuid = v.uuid
this.getBLEDeviceCharacteristics(v)
}
})
}
})
},
// 获取特征值
getBLEDeviceCharacteristics(item) {
let deviceId = this.deviceId
let serviceId = item.uuid
uni.getBLEDeviceCharacteristics({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId,
success: (res) => {
console.log('获取特征值成功', res)
res.characteristics = res.characteristics || []
// 必须在这里的回调才能获取
this.onBLECharacteristicValueChange()
res.characteristics.forEach(v => {
if (v.properties.read) {
console.log("自动读取数据", v)
this.readBLECharacteristicValue(v.uuid)
}
if (v.properties.notify || v.properties.indicate) {
console.log("特征值变化", v)
this.notifyBLECharacteristicValueChange(v.uuid)
}
})
// res.characteristics = res.characteristics.filter(v => {
// // read 读取 notify 通知 indicate 表明
// return v.properties.notify || v.properties.indicate
// })
// this.characteristics = res.characteristics
}
})
},
set_tezheng_uuid(item) {
this.tezheng_uuid = item.uuid
if (item.properties.read) {
console.log(this.tezheng_uuid, "支持读取")
}
},
// 写入数据
writeBLECharacteristicValue() {
// 向蓝牙设备发送一个0x00的16进制数据
const buffer = new ArrayBuffer(this.text_val)
const dataView = new DataView(buffer)
dataView.setUint8(0, 0)
let deviceId = this.deviceId
let serviceId = this.fuwu_uuid
let characteristicId = this.tezheng_uuid
uni.writeBLECharacteristicValue({
// 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId,
// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId,
// 这里的value是ArrayBuffer类型
value: buffer,
success: (res) => {
console.log('写入成功', res)
}
})
},
// 读取数据
readBLECharacteristicValue(characteristicId) {
let deviceId = this.deviceId
let serviceId = this.fuwu_uuid
// let characteristicId = characteristicId
console.log(222, {
deviceId,
serviceId,
characteristicId,
})
if (!serviceId) {
return console.log("没有服务")
} else if (!characteristicId) {
return console.log("没有特征值")
}
uni.readBLECharacteristicValue({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId,
// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId,
success: (res) => {
console.log('读取成功', res)
}
})
},
// 启用低功耗蓝牙设备特征值变化时的 notify 功能,订阅特征值
notifyBLECharacteristicValueChange(characteristicId) {
let deviceId = this.deviceId
let serviceId = this.fuwu_uuid
uni.notifyBLECharacteristicValueChange({ //开启通知
deviceId,
serviceId,
characteristicId: characteristicId,
state: true,
success: (res) => {
console.warn('特征值变化成功', res)
},
fail: (err) => {
console.log(err)
}
})
},
// 监听低功耗蓝牙设备的特征值变化事件
onBLECharacteristicValueChange() {
// #ifdef APP-PLUS
// 监听低功耗蓝牙设备的特征值变化
plus.bluetooth.onBLECharacteristicValueChange(function(characteristic) {
console.log('监听读取数据', characteristic)
let aa = ab2Str(characteristic.value)
if (aa) {
uni.showModal({
content: aa,
})
}
// console.log('onBLECharacteristicValueChange: ' + JSON.stringify(e));
// var value = buffer2hex(e.value);
// console.log('value(hex) = ' + value);
// if (characteristicId == e.characteristicId) {
// // 更新到页面显示
// alert('特征值变化: ' + value);
// }
});
// #endif
// #ifndef APP-PLUS
uni.onBLECharacteristicValueChange((characteristic) => {
console.log('监听读取数据', characteristic)
// console.log(111, new Uint8Array(characteristic.value))
// console.log(333, ab2hex(characteristic.value))
let aa = ab2Str(characteristic.value)
if (aa) {
uni.showModal({
content: aa,
})
}
})
// #endif
}
}
}
</script>
<style scoped lang="less">
.list_box {
height: 750rpx;
width: 750rpx;
box-sizing: border-box;
padding: 20rpx;
}
</style>