uniapp·链接蓝牙 获取数据
//1.初始化蓝牙模块
const tapLinkBluetooth = (v) => {
console.log("1.初始化蓝牙模块")
uni.openBluetoothAdapter({
success: function(res) {
uni.showToast({
title: '蓝牙已开启',
icon: 'success',
duration: 1000
});
tapSearchBluetooth();//开始搜索附近的蓝牙设备
},
fail: function(res) {
uni.showToast({
title: '请打开蓝牙',
type: 'error',
icon: 'none'
});
}
});
}
//2.开始搜索附近的蓝牙设备
let listBluetooth = ref([]);
const tapSearchBluetooth =()=>{
console.log("2.开始搜索附近的蓝牙设备")
uni.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
interval: 0,
success(res) {
console.log("搜索附近的蓝牙设备", res)
//提取蓝牙设备列表
console.log("3.提取蓝牙设备列表")
uni.getBluetoothDevices({
success(res) {
console.log('3.获取已搜索到的蓝牙设备列表', res);
listBluetooth.value = res.devices; //res.devices[0].connectable true==可链接
// tapThisBluetooth(listBluetooth.value[0]); //连接蓝牙
}
})
}
})
}
//4.指定某蓝牙并连接该蓝牙 (这里必须 嵌套执行)
const tapThisBluetooth = (v) => {
console.log("4.低功耗连接蓝牙:", v);
if (v && v.deviceId) {
uni.showLoading()
uni.createBLEConnection({
deviceId: v.deviceId,
success: function(res0) {
uni.hideLoading();
console.log('连接低功耗蓝牙设备:', res0)
if (res0 && res0.errMsg === 'createBLEConnection:ok') {
console.info("连接蓝牙设备 连接成功");
uni.stopBluetoothDevicesDiscovery(); //停止搜寻附近的蓝牙外围设备,避免低端设备卡顿
uni.showToast({title: '连接某蓝牙成功'});
uni.getBLEDeviceServices({
deviceId: v.deviceId,
success(res1) {
console.log('获取本蓝牙设备的所有服务:', res1.services)
uni.getBLEDeviceCharacteristics({
deviceId: v.deviceId,
serviceId: res1.services[1].uuid,
success(res2) {
console.log('获取蓝牙设备指定服务中所有特征值:', res2)
// console.log('特征值characteristics:', res2.characteristics)
let characteristicIds = [];
for (let vv of res2.characteristics) { //搜索可读取数据值
if (vv.properties.notify) {
characteristicIds.push(vv.uuid);
console.log('搜索可读取数据值:', vv)
}
}
for (let vv of characteristicIds) {
uni.notifyBLECharacteristicValueChange({
state: true, // 启用通知
deviceId: v.deviceId,
serviceId: res1.services[1]
.uuid, //49535343-ACA3-481C-91EC-D85E28A60318
characteristicId: vv,
success: function(res3) {
console.log('启用notify成功',res3);
uni.showToast({
title: '获取数据中',
icon: 'success',
});
// 监听特征值变化
uni.onBLECharacteristicValueChange(
function(res4) {
let x16 = ab2hex(res4.value);
let weight = hexToAscii(x16);
console.log("设备反馈值变化:", weight, x16);
})
},
fail: function(err) {
uni.showToast({
title: `${err.errMsg}`,
icon: 'none',
});
console.error('启用notify失败',err)
}
})
}
}
})
}
})
}
},
fail: (err) => {
uni.hideLoading();
console.log("连接蓝牙设备 连接失败");
uni.showToast({
title: `连接失败${err.errMsg}`,
icon: 'none',
});
}
});
} else {
uni.showToast({
title: '不可连接,无蓝牙设备ID',
icon: 'none',
});
}
}function ab2hex(buffer) {//二进制转16进制
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
}
function hexToAscii(hexString) { //16进制转明文
hexString = hexString.replace(/\s/g, '');
// 检查是否为有效的十六进制字符串
if (!/^[0-9a-fA-F]+$/.test(hexString)) {
throw new Error('Invalid hexadecimal string');
}
// 每两个字符分割,转换为ASCII字符
let ascii = '';
for (let i = 0; i < hexString.length; i += 2) {
const hexByte = hexString.substr(i, 2);
const charCode = parseInt(hexByte, 16);
ascii += String.fromCharCode(charCode);
}
return ascii;
}