详细问题描述
[内容]
前面的发现设备、连接获取设备相关信息、监听特征值都没有问题,到蓝牙写信息之后 onBLECharacteristicValueChange 没有监听到特征值的变化,而且连接蓝牙后第一次写好像是有效的(机器做出了反应),之后在写数据就无反应了。
重现步骤
[步骤]
1 开启手机蓝牙 开始调试
2 【查找设备】startBluetoothDevicesDiscovery
3 【测量】check01
[结果]
机器会开始测量(有时候不会测量),但是机器应该有特征值变化,但是监听不到。
在微信小程序调试工具里面一切正常。
[期望]
能够正常监控到特征值的变化,能够持续给机器发送指令。
[如果语言难以表述清晰,拍一个视频或截图,有图有真相]
IDE运行环境说明
HBuilderX 2.2.2.20190816
win10 专业版
uni-app运行环境说明
标准运行基座
HBuilderX创建的uni-app项目
App运行环境说明
[Android版本号]
Android 9
[手机型号]
redmi note7 pro
附件
[IDE问题请提供HBuilderX运行日志。菜单帮助-查看运行日志,点右键打开文件所在目录,将log文件压缩成zip包上传]
<template>
<view class="content">
<view class="" v-for="device in devicesList" :key="device">
<text>{{device.name}}</text>
</view>
<button type="primary" @tap="startBluetoothDevicesDiscovery">查找设备</button>
<!-- <button type="primary" @tap="pickUpOnce">监听</button> -->
<button type="primary" v-if="checkIsOk" @tap="check01">测量</button>
<button type="primary" v-if="checkIsOk" @tap="send00">信息读取包</button>
</view>
</template>
<script>
export default {
components: {},
data() {
return {
//是否已经打开蓝牙,默认为false,当蓝牙适配器初始化成功后为true
isOpenBle: false,
//设备列表
devicesList: [{
"name": "初始设备"
}],
checkIsOk: false,
//主服务的UUID
primaryUUID: "00001000",
//设备Id
deviceId: "",
//服务Id
serviceId: "",
// 支持写入操作的特征值
writeCharacteristicsId: "00001001-0000-1000-8000-00805F9B34FB",
// 支持notify操作的特征值
notifyCharacteristicsId: "00001002-0000-1000-8000-00805F9B34FB",
// 支持读取操作的特征值
readCharacteristicsId: "00001004-0000-1000-8000-00805F9B34FB",
}
},
onLoad() {
//在页面加载时候初始化蓝牙适配器
uni.openBluetoothAdapter({
success: e => {
console.log('初始化蓝牙成功:' + e.errMsg);
this.$data.isOpenBle = true;
console.log(this.$data.isOpenBle);
},
fail: e => {
console.log('初始化蓝牙失败,错误码:' + (e.errCode || e.errMsg));
}
});
//同时监听蓝牙连接状态
this.onBLEConnectionStateChange();
},
methods: {
// 监听
pickUpOnce() {
this.notifyBLECharacteristicValue();
},
// 检查
check01() {
this.writeBLECharacteristicValue(1);
},
// 发送信息
send00() {
this.writeBLECharacteristicValue(0);
},
startBluetoothDevicesDiscovery() {
//在页面显示的时候判断是都已经初始化完成蓝牙适配器若成功,则开始查找设备
let self = this;
setTimeout(function() {
if (self.isOpenBle) {
console.log("开始搜寻智能设备");
uni.startBluetoothDevicesDiscovery({
success: res => {
//
self.onBluetoothDeviceFound();
},
fail: res => {
console.log("查找设备失败!");
uni.showToast({
icon: "none",
title: "查找设备失败!",
duration: 3000
})
}
});
} else {
console.log("未初始化蓝牙是配饰器:" + self.isOpenBle);
}
}, 300);
},
/**
* 停止搜索蓝牙设备
*/
stopBluetoothDevicesDiscovery() {
uni.stopBluetoothDevicesDiscovery({
success: e => {
console.log('停止搜索蓝牙设备:' + e.errMsg);
},
fail: e => {
console.log('停止搜索蓝牙设备失败,错误码:' + e.errCode);
}
});
},
/**
* 发现外围设备
*/
onBluetoothDeviceFound() {
console.log("监听寻找新设备");
uni.onBluetoothDeviceFound(devices => {
console.log('开始监听寻找到新设备的事件');
this.getBluetoothDevices();
});
},
/**
* 获取在蓝牙模块生效期间所有已发现的蓝牙设备。包括已经和本机处于连接状态的设备。
*/
getBluetoothDevices() {
console.log("获取蓝牙设备");
uni.getBluetoothDevices({
success: res => {
console.log('获取蓝牙设备成功:' + res.errMsg);
this.devicesList = res.devices;
//在这里查找Belter_BT名称的血压仪
for (let i = 0; i < this.devicesList.length; i++) {
let eq = this.devicesList[i];
// console.log(res.devices);
if (eq.name === "Bioland-BPM") {
this.deviceId = eq.deviceId;
console.log("查找到了血压仪:设备deviceId:" + this.deviceId);
//在这准备连接设备
this.createBLEConnection();
//停止搜索设备
this.stopBluetoothDevicesDiscovery();
break;
}
}
},
fail: e => {
console.log('获取蓝牙设备错误,错误码:' + e.errCode);
}
});
},
/**
* 连接设备
*/
createBLEConnection() {
//设备deviceId
let deviceId = this.deviceId;
let self = this;
uni.createBLEConnection({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId,
success: res => {
console.log("设备连接成功!");
//延迟1.5s获取设备的services
setTimeout(function() {
console.log("获取设备的services");
self.getBLEDeviceServices();
}, 1500);
},
fail: res => {
console.log(JSON.stringify(res));
console.log("设备连接失败!");
}
});
},
/**
* 获取设备的服务ID
*/
getBLEDeviceServices() {
let deviceId = this.deviceId;
let serviceList = [];
let self = this;
uni.getBLEDeviceServices({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId,
success: res => {
console.log(JSON.stringify(res));
serviceList = res.services;
// console.log(serviceList);
for (let i = 0; i < serviceList.length; i++) {
let service = serviceList[i];
console.log(JSON.stringify(service) + "----serviceID:" + service.uuid);
//比对service是否是FFF0服务
if (service.uuid.indexOf(self.primaryUUID) != -1) {
self.serviceId = service.uuid;
console.log("设备的serviceId: " + self.serviceId);
//开始获取指定服务的特征值
self.getBLEDeviceCharacteristics();
break;
}
}
},
fail: res => {
console.log('device services:', res.services)
}
});
},
/**
* 获取指定服务的特征值
*/
getBLEDeviceCharacteristics() {
let deviceId = this.deviceId;
let serviceId = this.serviceId;
let characteristicsList = [];
let self = this;
// this.onBLECharacteristicValueChange();
uni.getBLEDeviceCharacteristics({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId,
success: res => {
console.log(JSON.stringify(res));
console.log("获取的" + serviceId + "服务的特征值:" + JSON.stringify(res.characteristics));
characteristicsList = res.characteristics;
for (let i = 0; i < characteristicsList.length; i++) {
let characteristic = characteristicsList[i];
//判断服务特征值中的特征值FFF3 和 FFF4
if (characteristic.uuid.indexOf("00001001") != -1) {
self.writeCharacteristicsId = characteristic.uuid;
console.log("设备的特征值写入ID: " + self.writeCharacteristicsId);
}
if (characteristic.uuid.indexOf("00001002") != -1) {
self.notifyCharacteristicsId = characteristic.uuid;
console.log("设备的特征值notifyID: " + self.notifyCharacteristicsId);
}
if (characteristic.uuid.indexOf("00001004") != -1) {
self.readCharacteristicsId = characteristic.uuid;
console.log("设备的特征值readId: " + self.readCharacteristicsId);
}
if (self.writeCharacteristicsId != "" && self.notifyCharacteristicsId != "" && self.readCharacteristicsId !=
"") {
console.log("--------------------特征值 获取完毕 开始监听 --------------------");
self.notifyBLECharacteristicValue();
self.onBLECharacteristicValueChange();
setTimeout(function() {
console.log("设备连接就绪 可以测量了");
self.checkIsOk = true;
}, 1500);
break;
}
}
},
fail: res => {
console.log('device getBLEDeviceCharacteristics failed:', JSON.stringify(res))
}
})
},
onBLECharacteristicValueChange() {
uni.onBLECharacteristicValueChange(function(res) {
console.log("特征值发生变化");
console.log(`characteristic ${res.characteristicId} has changed`)
});
},
/**
* 开启订阅特征值
*/
notifyBLECharacteristicValue() {
let deviceId = this.deviceId;
let serviceId = this.serviceId;
let characteristicId = this.notifyCharacteristicsId;
let notify = true;
let self = this;
uni.notifyBLECharacteristicValueChange({
state: true, // 启用 notify 功能
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId,
// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId,
success(res) {
console.log('notifyBLECharacteristicValueChange success:' + JSON.stringify(res));
},
fail(res) {
console.log('notifyBLECharacteristicValueChange failed:' + res.errMsg);
}
});
},
readBLECharacteristicValue() {
let deviceId = this.deviceId;
let serviceId = this.serviceId;
let characteristicId = this.readCharacteristicsId;
uni.readBLECharacteristicValue({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId,
// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId,
success(res) {
console.log('readBLECharacteristicValue:', JSON.stringify(res))
}
})
},
_getArrayBuffer(ty) {
let date = new Date();
let index0 = 90;
let index1 = 10;
let index2 = ty;
let index3 = date.getFullYear() % 100;
let index4 = date.getMonth() + 1;
let index5 = date.getDate();
let index6 = date.getHours();
let index7 = date.getMinutes();
let index8 = date.getSeconds();
let index9 = index0 + index1 + index2 + index3 + index4 + index5 + index6 + index7 + index8 + 2;
if (index9 > 255) {
index9 = index9 % 255;
}
let typedArray = new Uint8Array([index0, index1, index2, index3, index4, index5, index6, index7, index8, index9]);
return typedArray.buffer;
},
/**
* 写入控制命令
* writeCode 写入的控制命令
*/
writeBLECharacteristicValue(typesn) {
let deviceId = this.deviceId;
let serviceId = this.serviceId;
let characteristicId = this.writeCharacteristicsId;
const buffer = this._getArrayBuffer(typesn)
const dataView = new DataView(buffer)
console.log("发送的数据:")
for (let i = 0; i < dataView.byteLength; i++) {
console.log("0x" + dataView.getUint8(i).toString(16))
}
let that = this;
uni.writeBLECharacteristicValue({
// 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId,
// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
characteristicId,
// 这里的value是ArrayBuffer类型
value: buffer,
success(res) {
console.log('writeBLECharacteristicValue success', JSON.stringify(res))
// that.notifyCharacteristicValueChange();
// that.notifyBLECharacteristicValue();
that.readBLECharacteristicValue();
// that.onBLECharacteristicValueChange();
},
fail(res) {
console.log("写入数据失败", JSON.stringify(res))
}
});
},
/**
* 监听低功耗蓝牙连接状态的改变事件。包括开发者主动连接或断开连接,设备丢失,连接异常断开等等
*/
onBLEConnectionStateChange() {
let count = 0;
let that = this;
uni.onBLEConnectionStateChange(res => {
// 该方法回调中可以用于处理连接意外断开等异常情况
console.log(`蓝牙连接状态 -------------------------->`);
console.log(JSON.stringify(res));
if (!res.connected) {
console.log('断开低功耗蓝牙成功:');
uni.showModal({
title: '提示',
content: '蓝牙已断开是否重新连接',
success: function(res) {
if (res.confirm) {
//在这里尝试重连
that.createBLEConnection();
} else if (res.cancel) {
// 用户点击取消 关闭连接
that.closeBluetoothAdapter();
}
}
});
}
});
},
/**
* 断开蓝牙连接
*/
closeBluetoothAdapter() {
uni.closeBluetoothAdapter({
success: res => {
console.log('断开蓝牙模块成功');
uni.showToast({
icon: "none",
title: "蓝牙已经断开!",
mask: false,
duration: 3000
});
}
});
}
}
}
</script>
联系方式
251671021
[QQ]